抽象类和验证方法
向您介绍的 OOP 介绍性问题:
情况: 我想要一个带有公共 setter 和抽象验证器的抽象类,因为每个子级都会以独特的方式验证该属性。
代码:
abstract class Parent {
public function setName($name) {
if (validateName($name)) {
$this->_name = $name;
} else {
// error msg
}
}
abstract public function validateName($name);
}
class Child extends Parent {
public function validateName($name) {
// ensure name gits this child's requirements
}
}
问题:这是一种“合法”的设计方法吗?我认为由于每个子类的 setName 方法都是相同的,因此它应该是父类中的公共方法,但验证器应该是抽象的以强制子类实现它。
我只是在纸上概念性地勾勒出这个草图......
Introductory OOP question for you:
Situation: I want an abstract class with a public setter and abstract validator, since each child will validate that property in a unique way.
Code:
abstract class Parent {
public function setName($name) {
if (validateName($name)) {
$this->_name = $name;
} else {
// error msg
}
}
abstract public function validateName($name);
}
class Child extends Parent {
public function validateName($name) {
// ensure name gits this child's requirements
}
}
Question: is this a "legal" design approach? I figured since the setName
method will be the same for every child class, it should be a public method in the parent class, but the validator should be abstract to force child classes to implement it.
I'm just sketching this out on paper conceptually...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是一种有效的方法,尽管您的语法不完美:
应该是这样:
但如果这是架构的范围,为什么不直接定义抽象
setName()
来验证和设置它呢?像这样:当然我这里使用了一个接口,因为Parent中没有代码。
但请注意,这取决于您的程序的结构。我必须至少看到程序架构的图表才能确定哪种方式。
Yes, that's a valid approach, although your syntax in imperfect:
should be this:
But if this is the scope of the architecture, why not just define abstract
setName()
that validates and sets it? Like this:Of course I use an interface here, because there's no code in Parent.
But please realize, this depends on how you're program is structured. I'd have to see at least a diagram of the program's architecture to say definitely either way.