php,java实现装饰者模式

当需要为现有的类增加新的功能,或则需要包装现有类时,适合使用该模式

类图:
这里写图片描述

java实现
抽象产品类

public abstract class Subject {

    public abstract void doSomething();
}

产品类

public class ConcreteSubject extends Subject {

    @Override
    public void doSomething() {

    }
}

抽象装饰者

public abstract class Decoration extends Subject{

    private Subject subject = null;

    public Decoration(Subject subject){
        this.subject = subject;
    }

    @Override
    public void doSomething() {
        subject.doSomething();
    }
}

装饰者

public class ConcreteDecoration extends Decoration {


    public ConcreteDecoration(Subject subject) {
        super(subject);
    }

    private void decorationMethods(){

    }

    @Override
    public void doSomething() {
        decorationMethods();
        super.doSomething();
    }
}

php实现

abstract class Subject
{
    public abstract function doSomething();    
}

class ConcreteSubject extends Subject
{
    public function doSomething()
    {
        echo 'doSomething';
    }
}

abstract class Decortion extends Subject
{
    private $subject;

    public function __construct(Subject $subject)
    {
        $this->subject = $subject;
    }

    public function doSomething()
    {
        $this->subject->doSomething();
    }
}

class ConcreteDecortion extends Decortion
{
    public function __construct(Subject $subject)
    {
        parent::__construct($subject);
    }

    public function decortionMethods()
    {
        echo 'decortionMethods';
    }

    public function doSomething()
    {
        $this->decortionMethods();
        parent::doSomething();
    }
}

$decortion =  new ConcreteDecortion(new ConcreteSubject());
$decortion->doSomething();
阅读更多
版权声明:如有错误,恳请留言.... https://blog.csdn.net/renpengddxx/article/details/68137544
个人分类: 设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭