装饰模式

定义

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

装饰模式结构图

例子

  还是继续车子的例子,现在是组装汽车,在汽车上组装各种部件。

  Component(Component)

package com.csdhsm.designpattem.decorator;

/**  
 * @Title:  Component.java   
 * @Description: 
 * @author: Han   
 * @date:   2016年6月19日 下午3:54:59   
 */  
public interface Component {
    
    public void operation();
}

  Car(ConcreteComponent)

package com.csdhsm.designpattem.decorator;

/**  
 * @Title:  Car.java   
 * @Description: 汽车类
 * @author: Han   
 * @date:   2016年6月19日 下午3:55:42   
 */  
public class Car implements Component {
    
    private String name;

    public Car(String name) {
        this.name = name;
    }
    
    public void operation() {
        System.out.print("叫" + name + "的车");
    }
}

  Decorator(Decorator)

package com.csdhsm.designpattem.decorator;

/**  
 * @Title:  Decorator.java   
 * @Description: 给汽车装饰上配件
 * @author: Han   
 * @date:   2016年6月19日 下午3:56:22   
 */  
public class Decorator implements Component {

    private Component component;
    
    public void setComponent(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        if(this.component != null)
            this.component.operation();
    }
}

  Wheel(ConcreteDecorator)

package com.csdhsm.designpattem.decorator;

/**  
 * @Title:  Wheel.java   
 * @Description: 轮子类
 * @author: Han   
 * @date:   2016年6月19日 下午3:57:23   
 */  
public class Wheel extends Decorator {

    @Override
    public void operation() {
        System.out.print("装上轮子的  ");
        super.operation();
    }
}

  Engine(ConcreteDecorator)

package com.csdhsm.designpattem.decorator;

/**  
 * @Title:  Engine.java   
 * @Description: 发动机类
 * @author: Han   
 * @date:   2016年6月19日 下午3:57:32   
 */  
public class Engine extends Decorator {

    @Override
    public void operation() {
        System.out.print("装上发动机的   ");
        super.operation();
    }
}

  客户端代码

package com.csdhsm.designpattem.decorator;

public class Solution {
    
    public static void main(String[] args) {
        
        Component car = new Car("小旋风");
        Decorator wheel = new Wheel();
        Decorator engine = new Engine();
        
        wheel.setComponent(car);
        engine.setComponent(wheel);
        
        engine.operation();
    }
}

  看了很多例子之后,就感觉像是向一个具体的对象上包装功能,一层一层的包装上去,这样,最后这个对象上就有了各种功能,ConcreteComponent就是这个具体的对象,而Decorator用来扩展该对象的功能,而继承自Decorator类的对象都是ConcreteDecorator,将要被包装到具体对象上的具体的功能。

 posted on 2016-06-19 16:03  韩思明  阅读(145)  评论(0编辑  收藏  举报