创建子类的对象实例的设计模式
我有一个存储人员和公司的 MySQL 表。他们有相同的领域。在 php 中,我有
class User{
var $_id;
var $_data;
function loadDataFromDb()
{
}
}
class Company extends User
{
function getName()
{
//some implemantation
}
}
class People extends User
{
function getName()
{
//some implemantation
}
}
什么是创建对象的最佳方法。当我创建对象时,我不知道客户端是哪种类型。
我需要类似的东西:
$user = /* code missing */
$user->getName(); // this will trigger the appropiate method.`
I have a MySQL table that stores people and companies. They have same fields. In php I have
class User{
var $_id;
var $_data;
function loadDataFromDb()
{
}
}
class Company extends User
{
function getName()
{
//some implemantation
}
}
class People extends User
{
function getName()
{
//some implemantation
}
}
What is the best way of creating the objects. When I creat my object I am not aware of which type of client is.
I need something like:
$user = /* code missing */
$user->getName(); // this will trigger the appropiate method.`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为工厂方法适合当前情况,因为该工厂将为您提供您正在寻找的对象。
您必须传递某种信息才能让工厂决定应返回哪个对象。
I think a factory method will be suitable for the present case as this factory will give you the object you are looking for.
You have to pass some kind of information though to let factory decide which object should be returned.
抽象工厂模式:
Abstract Factory pattern:
您可以使用像 Doctrine 这样的 ORM 来完成此类工作吗?它支持继承,因此您可以将其映射到数据库模式(这应该是 Doctrine 中的具体继承类策略)。
否则,请尝试澄清您的目标和具体问题。
How about you use an ORM like Doctrine for this sort of work. It supports inheritance so you could map this to you database schema (this should be concrete inheritance class strategy in Doctrine).
Otherwise, try to clarify what is your goal and concrete problem here.