我正在学习设计模式。你能帮我为这个类设计一个工厂模式吗?
我有一个从其他类的层次结构构建的类,并且我创建了一堆相同的类,除了类名之外,它们看起来相同
但是
class Class1 extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
class Class2 extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
class Class3 extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
我意识到(希望是正确的)我可以使用创建 Class[1-3]工厂模式,只需传递一个类名并让工厂返回这些类之一。这将需要更少的代码,因此更易于维护。另外,如果说我想这样做,你会建议如何实现:
class Class4 extends AnotherBaseClass
{
public function __construct()
{
parent::__construct();
}
}
请注意,类 4 扩展了另一个基类,但除了 AnotherBaseClass 保存的一小部分信息之外,它是完全相同的。
现在我在想这样的事情(我的想法在这一点上是模糊和不完整的):
//我放置重复代码的地方
class Skeleton extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
class ClassFactory
{
public function __construct( $className , $classType )
{
<pseudocode>
Class5 = new $className
???and some how make $className extend $classType ???
return class5
</pseudocode>
}
}
工厂模式是正确的答案吗?
干杯!
I have a class built from a hierarchy of other classes, and I had created a bunch of the same classes that looked identical other than the class name
for example
class Class1 extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
class Class2 extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
class Class3 extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
But I realize (hopefully rightfully) that I could create Class[1-3] using a factory pattern, and just pass a class name and have the factory return one of these classes. This would require much less code, thus more maintainable. Also, how would you suggest implementing if say I wanted to do this :
class Class4 extends AnotherBaseClass
{
public function __construct()
{
parent::__construct();
}
}
note that class 4 extends another base class, but it is the exact same other than a small bit of information that AnotherBaseClass holds.
right now i am thinking something like this (my thoughts are fuzzy and incomplete at this point):
//where i am putting the repeating code
class Skeleton extends BaseClass
{
public function __construct()
{
parent::__construct();
}
}
class ClassFactory
{
public function __construct( $className , $classType )
{
<pseudocode>
Class5 = new $className
???and some how make $className extend $classType ???
return class5
</pseudocode>
}
}
Is the factory pattern the correct answer?
Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的 - 工厂模式是正确的答案。此外,您还可以查看 Abstract Factory,专门针对您提到的某些类将具有不同的场景属性,并且可以从其他一些基类派生。
Yes - factory pattern is the correct answer. In addition you may also check out Abstract Factory, specifically for the scenario you mentioned where your some classes will have different attributes and may derive from some other base class.