现在的位置: 首页 > 综合 > 正文

JAVA设计模式之装饰模式

2018年05月12日 ⁄ 综合 ⁄ 共 2075字 ⁄ 字号 评论关闭

装饰模式(Decorator):

 装饰模式的角色有:

—— 抽象构件角色(Component):给出一个抽象接口,以规范准备接收附加责任的对象。

—— 具体构件角色(Concrete Component):定义一个将要接收附加责任的类。

—— 装饰角色(Decorator):持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口。

—— 具体装饰角色(Concrete Decorator):负责给构件对象“贴上”附加的责任。

装饰模式的特点:

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

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

—— 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。

面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

装饰模式 vs 继承

。装饰模式

—— 用来扩展特定 对象 的功能

—— 动态

—— 运行时分配职责

—— 防止由于子类而导致的复杂和混乱

—— 更多的灵活性

—— 对于一个给定的对象,同时可能有不同的装饰对象,客户端可以通过它的需要选择合适的装饰对象发送消息。

。继承

—— 用来扩展 一类的对象的功能
—— 需要子类

—— 静态

—— 编译时分派职责

—— 导致很多子类产生

—— 缺乏灵活性package com.tb.pattern;

public interface Component {
    public void doSomething();
}

package com.tb.pattern;

public class ConcreteComponent implements Component {

    @Override
    public void doSomething() {
        System.out.println("功能A");
    }

}

package com.tb.pattern;

public class Decorator implements Component {
    
    private Component component;
    
    public Decorator(Component component) {
        this.component = component;
    }
    
    @Override
    public void doSomething() {
        component.doSomething();
    }

}

package com.tb.pattern;

public class ConcreteDecorator1 extends Decorator {
    public ConcreteDecorator1(Component component) {
        super(component);
    }
    
    @Override
    public void doSomething() {
        super.doSomething();
        
        this.doAnotherThing();
    }

    private void doAnotherThing() {
        System.out.println("功能B");
    }
}

package com.tb.pattern;

public class ConcreteDecorator2 extends Decorator {

    public ConcreteDecorator2(Component component) {
        super(component);
    }
    
    @Override
    public void doSomething() {
        super.doSomething();
        
        this.doAnotherThing();
    }

    private void doAnotherThing() {
        System.out.println("功能C");
    }
}

package com.tb.pattern;

public class Client {
    
    public static void main(String[] args) {
        
        //节点流
        Component component = new ConcreteComponent();
        
        //过滤流
        Component component2 = new ConcreteDecorator1(component);
        
        //过滤流
        Component component3 = new ConcreteDecorator2(component2);
        
        component3.doSomething();
    }
}

运行结果

功能A
功能B
功能C

综上:装饰模式比较简单,但是比较实用。可以在不用继承的情况下,扩展原有对象的功能。该模式简单明了,需要牢牢记住!

抱歉!评论已关闭.