JavaJava设计模式

设计模式-装饰者模式

2019-04-11  本文已影响5人  smallmartial

装饰者模式概念:

装饰者模式又名包装(Wrapper)模式。装饰者模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

装饰者模式动态地将责任附加到对象身上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

装饰模式的结构

装饰者模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰者模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。

装饰者模式UML类图:


装饰者模式类图

装饰者模式中的角色有:

装饰模式实例演示:

儿子、妈妈、父亲三人合作画一幅画,儿子负责画出一朵花的轮廓,妈妈负责涂上颜色、父亲负责将画裱在画框里。请编写程序模拟这个过程。UML类图如下:


UML

代码实现:
接口类:

public interface Painter {

    public void draw();
}

具体构建son类:

public class Son implements Painter {

    @Override
    public void draw() {
        System.out.println("我是儿子,我花了花的轮廓");
    }
}

抽象角色Decorater类:

public abstract class Decorator implements Painter {

    private Painter painter;
    
    public Decorator(Painter painter) {
        this.painter = painter;
    }

    public void draw() {
        painter.draw();
    }

}

具体装饰角色mother:

public class Mother extends Decorator {
    
    public Mother(Painter painter) {
        super(painter);
    }

    public void draw() {
        super.draw();
        System.out.println("Mother Draw");
        this.color();

    }
    
    public void color(){
        System.out.println("我是妈妈,我给画涂色");
    }
}

具体装饰角色father:

public class Father extends Decorator {
    public Father(Painter painter) {
        super(painter);
    }
    public void draw() {
        super.draw();
        System.out.println("Father Draw");
        this.mounting();
    
    }
    public void mounting(){
        System.out.println("我是爸爸,我将画裱起来");
    }
}

实现类:

public class Application {
    public static void main(String[] args) {
        Painter son = new Son();
        son.draw();
        Decorator son1=new Mother(son); 
        son1.draw();
        Decorator son2=new Father(son); 
        son2.draw();
    
        //System.out.println();
    
    }
}

运行结果:


result.png

装饰者模式的优缺点

装饰者模式的优点:

装饰者模式的缺点:

上一篇下一篇

猜你喜欢

热点阅读