问题描述
我经常发现自己创建使用这种形式(A)的类: abstract class Animal {
public void Walk(){
// TODO:在执行之前执行某些操作
//每个子类实现的自定义逻辑
WalkInternal();
// TODO:行走后做一些
}
protected abstract void WalkInternal();
}
class Dog:Animal {
protected override void WalkInternal(){
// TODO:walk with 4 legs
}
}
class Bird:Animal {
protected override void WalkInternal(){
// TODO:walk with two legs
}
}
而不是这种形式(B):
抽象类Animal {
public abstract void Walk();
}
class Dog:Animal {
public override void Walk(){
// TODO:在走路前做点事
/ /每个子类实现的自定义逻辑
// TODO:步行4条腿
// TODO:在走路之后执行某些操作
}
}
class Bird:Animal {
public override void Walk(){
// TODO:执行某些操作之前
//由每个子类实现的自定义逻辑
// TODO:步行2条腿
// TODO:走路后做点事
}
}
如您所见,表单A的好处是每次实现子类时,都不需要记住包含初始化和终止逻辑。这比窗体B更容易出错。
命名这些方法的标准惯例是什么?
我喜欢命名公共方法步行
从那以后,我可以调用 Dog.Walk()
,看起来比 Dog.WalkExternal()
。但是,我不喜欢我的解决方案为protected方法添加后缀Internal。我正在寻找一个更加标准化的名称。
Btw,这个设计模式有没有名字?
我不知道是否有一个标准的命名约定。除了 WalkInternal
,其他替代方案可能是 DoWalk
或 WalkImpl
。
I frequently find myself creating classes which use this form (A):
abstract class Animal {
public void Walk() {
// TODO: do something before walking
// custom logic implemented by each subclass
WalkInternal();
// TODO: do something after walking
}
protected abstract void WalkInternal();
}
class Dog : Animal {
protected override void WalkInternal() {
// TODO: walk with 4 legs
}
}
class Bird : Animal {
protected override void WalkInternal() {
// TODO: walk with 2 legs
}
}
Rather than this form (B):
abstract class Animal {
public abstract void Walk();
}
class Dog : Animal {
public override void Walk() {
// TODO: do something before walking
// custom logic implemented by each subclass
// TODO: walk with 4 legs
// TODO: do something after walking
}
}
class Bird : Animal {
public override void Walk() {
// TODO: do something before walking
// custom logic implemented by each subclass
// TODO: walk with 2 legs
// TODO: do something after walking
}
}
As you can see, the nice thing about form A is that every time you implement a subclass, you don't need to remember to include the initialization and finalization logic. This is much less error prone than form B.
What's a standard convention for naming these methods?
I like naming the public method Walk
since then I can call Dog.Walk()
which looks better than something like Dog.WalkExternal()
. However, I don't like my solution of adding the suffix "Internal" for the protected method. I'm looking for a more standardized name.
Btw, is there a name for this design pattern?
I'm not sure if there is a standard naming convention for this. Besides WalkInternal
, other alternatives might be DoWalk
or WalkImpl
.
这篇关于非虚拟和抽象方法的命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!