装饰者模式的实现:装饰者模式是在不必改变原类文件和使用继承的情况下,动态扩展一个对象的功能,它是通过创建一个包装对象,来装饰和包裹真实的对象。
优点:装饰者模式和继承关系都是要扩展对象的功能,但装饰者模式可以提供比继承更多的灵活性。
缺点:灵活性是更好了,却增加了对象的复杂性
5.创建测试类Test
优点:装饰者模式和继承关系都是要扩展对象的功能,但装饰者模式可以提供比继承更多的灵活性。
缺点:灵活性是更好了,却增加了对象的复杂性
装饰者模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。
还是举个例子比较容易理解:
1.创建IthirdParty接口
package decorator;
/**
* 抽象类接口
* @author lyh
*
*/
public interface IthirdParty {
public String sayMsg();
}
2.创建IthirdParty接口的实现类 ThirdParty
package decorator;
/**
* 具体类
* @author lyh
*
*/
public class ThirdParty implements IthirdParty{
@Override
public String sayMsg() {
return "Hello";
}
}
3.创建ThirdParty的装饰类Decorator1,也实现IthirdParty接口
package decorator;
/**
* 具体装饰类1
* @author lyh
*
*/
public class Decorator1 implements IthirdParty{
private IthirdParty thirdParty;
public Decorator1(IthirdParty thirdParty){
this.thirdParty=thirdParty;
}
@Override
public String sayMsg() {
return "##1"+thirdParty.sayMsg()+"##1";
}
}
4.创建ThirdParty的装饰类Decorator2,也实现IthirdParty接口
package decorator;
/**
* 具体装饰类2
* @author lyh
*
*/
public class Decorator2 implements IthirdParty{
private IthirdParty ithirdParty;
public Decorator2(IthirdParty ithirdParty){
this.ithirdParty=ithirdParty;
}
@Override
public String sayMsg() {
return "##2"+ithirdParty.sayMsg()+"##2";
}
}
5.创建测试类Test
package decorator;
/**
* @author lyh
*
*/
public class Test {
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());
}
}