在过去的几年里,我参与的项目在我们的对象层次结构中遇到了类似的问题,似乎总是会导致问题。我很好奇这里是否有人知道可以优雅地处理这种情况的经典 OOP(Java、C#、PHP5 等)设计模式。
假设我们有一个现有系统。这个系统有两种类型的实体,每一种都用一个单独的类建模。假设
客户
销售代表
由于历史原因,这些类都没有继承自同一个基类或共享一个公共(public)接口(interface)。
我看到的问题是,不可避免地会指定一个新功能,要求我们将 Customer 和 SalesRepresentative 视为同一类型的对象。我过去看到的这种处理方式是创建一个新类,其中包含一个用于两者的成员变量,然后每个方法将根据设置的不同对对象进行不同的操作
//pseudo PHPish code
class Participator
{
public $customer;
public $salesRepresentative;
public function __construct($object)
{
if(object is instance of Customer)
{
$this->customer = $object;
}
if(object is instance of SalesRepresentative)
{
$this->salesRepresentative = $object;
}
}
public function doesSomething()
{
if($customer)
{
//We're a customer, do customer specific stuff
}
else if($salesRepresentative)
{
//We're a salesRepresentative, do sales
//representative specific stuff
}
}
}
有没有更优雅的方式来处理这种情况?
最佳答案
也许这里可以使用 Wrapper。创建一个包装器接口(interface),比如指定新功能的 ParticipatorWrapper,并为每个类构建具体的包装器,比如都实现新功能的 CustomerWrapper 和 SalesRepresentativeWrapper。
然后简单地将对象包装在其适当的包装器中并编写以 ParticipatorWrapper 为目标的代码。
更新:Javaish 代码:
interface ParticipatorWrapper{
public void doSomething();
}
class CustomerWrapper implements ParticipatorWrapper{
Customer customer;
public void doSomething(){
//do something with the customer
}
}
class SaleREpresentativeWrapper implements ParticipatorWrapper{
SaleRepresentative salesRepresentative;
public void doSomething(){
//do something with the salesRepresentative
}
}
class ClientOfWrapper{
public void mymethod(){
ParticipatorWrapper p = new ParticipatorWrapper(new Customer());
p.doSomething();
}
}
关于c# - 处理将相似实体分组在一起的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1434062/