设计模式之装饰模式
装饰模式,是为已有功能动态地添加跟多功能的一种方式。当系统需求新的功能的时候,是向旧的类中添加新的代码,这些新的代码通常装饰了原来类的核心职责或者是主要功能。那是用装饰模式那就比较好的去处理这些问题。
举个例子
小明去约会找对象,想自己去找对象,不想那么随便,那就想穿的好看一点去,给女生留下一个好的影响。那他可能有多种穿法,那用代码写出来。
装饰模式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();
}
}
测试结果:
小明
外套
裤子
小明遇到我这样不负责的程序员,他找到对象的概率不会很大了。算是对装饰模式理解的差不多了。