装饰者模式-大话设计模式

简介: 装饰者模式-大话设计模式

一、定义

装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

二、特点

(1) 装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。

(2) 装饰对象包含一个真实对象的引用(reference)

(3) 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。

(4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

三、类结构图及说明

 

Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无须知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。

四、代码实现

public abstract class Component {
    public abstract void Operation();
}
public class ConcreteComponent extends Component {
    @Override
    public void Operation() {
        System.out.println("具体对象的实际操作");
    }
}
public class ConcreteDecoratorA extends Decorator{
    @Override
    public void Operation() {
        super.Operation();
        System.out.println("A类特有方法");
    }
}
public class ConcreteDecoratorB extends Decorator{
    @Override
    public void Operation() {
        super.Operation();
        System.out.println("B类特有方法");
    }
}
public class ConcreteDecoratorC extends Decorator{
    @Override
    public void Operation() {
        super.Operation();
        System.out.println("C类特有方法");
    }
}
//装饰抽象类
public class Decorator extends Component {
    protected Component component;
    //装饰一个Component对象
    public void setComponent(Component component) {
        this.component = component;
    }
    //重写Operation(),实际调用
    @Override
    public void Operation() {
        if (component != null) {
            component.Operation();
        }
    }
}

调用

    public static void main(String[] args) {
        ConcreteComponent c=new ConcreteComponent();
        ConcreteDecoratorA d1=new ConcreteDecoratorA();
        ConcreteDecoratorB d2=new ConcreteDecoratorB();
        ConcreteDecoratorC d3=new ConcreteDecoratorC();
        d1.setComponent(c);
        d2.setComponent(d1);
        d3.setComponent(d2);
        d3.Operation();
    }
具体对象的实际操作
A类特有方法
B类特有方法
C类特有方法

相关文章
|
3月前
|
设计模式
适配器模式-大话设计模式
适配器模式-大话设计模式
|
3月前
|
设计模式
中介者模式-大话设计模式
中介者模式-大话设计模式
|
3月前
|
设计模式 算法
建造者模式-大话设计模式
建造者模式-大话设计模式
|
3月前
|
设计模式 搜索推荐
工厂方法模式-大话设计模式
工厂方法模式-大话设计模式
|
4月前
|
设计模式 uml
大话设计模式(3)——造物者一般的建造者模式
大话设计模式(3)——造物者一般的建造者模式
34 1
大话设计模式(3)——造物者一般的建造者模式
|
3月前
|
设计模式
外观模式-大话设计模式
外观模式-大话设计模式
|
3月前
|
设计模式 算法
模板方法-大话设计模式
模板方法-大话设计模式
|
3月前
|
设计模式
简单工厂模式-大话设计模式
简单工厂模式-大话设计模式
|
设计模式
【大话设计模式】结构型模式总结
【大话设计模式】结构型模式总结
|
设计模式
大话设计模式之装饰模式
大话设计模式之装饰模式