设计模式之装饰模式

设计模式之装饰模式

装饰模式,是为已有功能动态地添加跟多功能的一种方式。当系统需求新的功能的时候,是向旧的类中添加新的代码,这些新的代码通常装饰了原来类的核心职责或者是主要功能。那是用装饰模式那就比较好的去处理这些问题。

举个例子
小明去约会找对象,想自己去找对象,不想那么随便,那就想穿的好看一点去,给女生留下一个好的影响。那他可能有多种穿法,那用代码写出来。

装饰模式UML图
装饰模式UML图

package com.shejimoshi.zhuangshimoshi;
/**
 * 展示借口
 * @author chenjingbin
 *
 */
public interface Show {
    /**
     * 展示方法Show
     */
    void show();
}

package com.shejimoshi.zhuangshimoshi;
/**
 * 人类,实现Show接口
 * @author chenjingbin
 *
 */
public class Person implements Show {
    private String name;
    public Person(String name){
        this.name = name ;
    }
    @Override
    public void show() {
        // TODO Auto-generated method stub
        System.out.println( name);
    }

}

package com.shejimoshi.zhuangshimoshi;
/**
 * 衣服类,实现Show接口
 * @author chenjingbin
 *
 */
public class Cloth implements Show {
    protected Show show;

    public Cloth(Show show){
        this.show=show;
    }
    @Override
    public void show() {
        // TODO Auto-generated method stub
        show.show();
    }

}

package com.shejimoshi.zhuangshimoshi;

/**
 * 外套类,继承Cloth类
 * 
 * @author chenjingbin
 * 
 */
public class Garments extends Cloth {

    public Garments(Show show) {
        super(show);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void show() {
        // TODO Auto-generated method stub
        super.show();
        System.out.println("外套");
    }

}

package com.shejimoshi.zhuangshimoshi;

/**
 * 裤子类,继承cloth类
 * @author chenjingbin
 *
 */
public class Trousers extends Cloth {

    public Trousers(Show show) {
        super(show);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void show() {
        // TODO Auto-generated method stub
        super.show();
        System.out.println("裤子");
    }

}

package com.shejimoshi.zhuangshimoshi;

import org.junit.Test;

/**
 * 测试类
 * @author chenjingbin
 *
 */
public class DemoTest {
    @Test
    public void test(){
        Show show = new Person("小明");
        Cloth cloth = new Garments(show);
        Cloth cloth2 = new Trousers(cloth);
        cloth2.show();
    }
}



测试结果:
        小明
        外套
        裤子

小明遇到我这样不负责的程序员,他找到对象的概率不会很大了。算是对装饰模式理解的差不多了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值