总体来说设计模式分为三大类:
创建型模式5种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式7种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式11种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
装饰器模式
Demo
在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
在装饰模式中的各个角色有:
①抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
②具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
③装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
④具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。
首先,定义一个公共的接口
public interface IthirdParty {
public String sayMsg();
}
其次,编写实体类
public class ThirdParty implements IthirdParty {
public String sayMsg() {
return "hello";
}
}
然后,编写装饰类类
装饰类1
public class Decorator1 implements IThirdParty {
private IThirdParty thirdParty;
public Decorator1(IThirdParty thirdParty){
this.thirdParty= thirdParty;
}
public String sayMsg(){
return "##1"+ thirdParty.sayMsg() + "##1";
}
}
装饰类2
public class Decorator2 implements IThirdParty {
private IThirdParty thirdParty;
public Decorator2(IThirdParty thirdParty){
this.thirdParty= thirdParty;
}
public String sayMsg(){
return "##2"+ thirdParty.sayMsg() + "##2";
}
}
接着,编写测试类
public class MailTest {
public static void main(String[] args){
IthirdParty thirdPartyOne =new ThirdParty();
IthirdParty decorator1 =new Decorator1(thirdPartyOne);
IthirdParty decorator2 =new Decorator2(decorator1);
System.out.println(decorator2.sayMsg());
}
}
最后,查看结果
##2##1hello##1##2