Android知识Android开发Android技术知识

装饰模式

2017-04-30  本文已影响76人  程序员丶星霖

装饰模式

定义

是一种比较常见的模式,动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。

英文定义:Attach additional responsibilities to an object dynamically keeping the same interface . Decorators provide a flexible alternative to subclassing for extending functionality .

装饰模式的UML类图如下所示:

装饰模式.jpg

上图中涉及到的角色包括:

示例代码如下所示:

//抽象构件
public abstract class Component{
    //抽象的方法
    public abstract void operate();
}
//具体构件
public class ConcreteComponent extends Component{
    //具体实现
    @Override
    public void operate(){
        System.out.println("do  Something");
    }
}
//抽象装饰者
public abstract class Decorator extends Component{
    private Component component = null;
    //通过构造函数传递被修饰者
    public Decorator(Component component){
        this.component = component;
    }
    //委托给被修饰者执行
    @Override
    public void operate(){
        this.component.operate();
    }
}
//具体的装饰类
public class ConcreteDecorator1 extends Decorator{
    //定义被修饰者
    public ConcreteDecorator1(Component component){
        super(component);
    }
    //定义自己的修饰方法
    private void method1(){
        System.out.println("method1修饰");
    }
    //重写父类的Operation方法
    public void operate(){
        this.method1();
        super.operate();
    }
}
public class ConcreteDecorator2 extends Decorator{
    //定义被修饰者
    public ConcreteDecorator2(Component component){
        super(component);
    }
    //定义自己的修饰方法
    private void method2(){
        System.out.println("method1修饰");
    }
    //重写父类的Operation方法
    public void operate(){
        this.method2();
        super.operate();
    }
}
//场景类
public class Client{
    public static void main(String[] args){
        Component component = new ConcreteComponent();
        //第一次修饰
        component = new ConcreteDecorator1(component);
        //第二次修饰
        component = new ConcreteDecorator2(component);
        //修饰后运行
        component.operate();
    }
}

优缺点

优点:

缺点:

使用场景:

二维码走一波!

我的微信公众号.jpg
上一篇 下一篇

猜你喜欢

热点阅读