处理将相似实体分组的设计模式

Ala*_*orm 2 php c# java oop design-patterns

在过去的几年里,我一直在处理我们在对象层次结构中遇到类似问题的项目,这些问题总是会导致问题.我很好奇,如果有人知道经典的OOP(Java,C#,PHP5等)设计模式可以优雅地处理这种情况.

假设我们有一个现有系统.除其他外,该系统具有两种类型的实体,每种实体都用单独的类建模.让我们说吧

  1. 顾客

  2. 销售代表

由于历史原因,这些类都不从相同的基类继承或共享公共接口.

我看到的问题是,不可避免地会出现一个新功能,要求我们将Customer和SalesRepresentative视为相同类型的Object.我在过去看到这个处理的方式是创建一个包含两个成员变量的新类,然后每个方法将根据设置的不同对对象进行操作

//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
        }           
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方式来处理这种情况?

Vin*_*nie 8

也许这里可以使用Wrapper.创建一个包装器接口,例如ParticipatorWrapper,它指定新功能并为每个类构建具体的Wrappers,比如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();
   }
}
Run Code Online (Sandbox Code Playgroud)