doubeizhong5178 2013-11-09 22:45
浏览 80

我可以重复使用装饰器吗?

Can I reuse decorators?

I have a ClientDecorator to decorate an entity that has a reference of a client, this decorator gets the client on database on call getClient (before it gets decorated, this method returns the clientId, after being decorated, it returns an instance of Client).

Okay, but, I've some other entities that can be decorated with the same decorator, for example, I have another table named questions, this table has a reference pointing to a client that has asked a question, and I have another table named schedules, that has a reference of a client.

By the way, I can decorate question and schedule with ClientDecorator.

But, I have an QuestionDecorator too; this guy decorates an Answer, etc.

How I can do this abstraction, so I can reuse decorators whenever I want?

I've tried to create ClientDecorable, QuestionDecorable interfaces, but have made no progress.

  • 写回答

2条回答 默认 最新

  • dtkz3186 2013-11-09 22:55
    关注

    You can always instance the decorator class passing parameters to the constructor that will tell it how it should behave or what class it should impersonate. You don't really have to declare your decorator as an extension of another class.

    PHP classes support magic methods that make it possible to forward calls to the class your object is impersonating, just as if it was extending it with extends.

    For instance:

    class Client
    {
        public function getId() { return 123; }
    }
    
    class Decorator
    {
        private $instance = null;
    
        public function __construct($class)
        {
            $this->instance = new $class();
        }
    
        public function __call($method, $params) // magic method
        {
            return call_user_func_array(array($this->instance, $method), $params);
        }
    }
    
    $object = Decorator('Client');
    echo $object->getId(); // 123
    

    The magic method __call() will be invoked when you try to access a method that doesn't belong to the class Decorator. The same can be done with properties by using the magic methods __get() and __set().

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测