java设计模式--装饰模式

装饰模式:就是动态地给一个对象添加一些额外的职责(功能)。那么如何动态的给一个对象添加功能呢,以下给出了例子。

//Person是一个对象接口,我们的目的是给实现这个接口的对象动态的添加职责
public
interface Person {    //定义一了一个装饰的方法 void decorate(); }
//实现接口的具体对象,我们现在就要给这个类“穿衣服”
public class ConcretePerson implements Person { @Override public void decorate() { System.out.println("穿衣服的人"); } }
//装饰的抽象类,使装饰功能与主类的逻辑区分开
public abstract class Clothes implements Person { protected Person component; public Clothes(Person component){ this.component = component; } @Override public void decorate(){ if(component!=null){ component.decorate(); } } } //具体的装饰类,给Person类添加职责 public class Tshirt extends Clothes { public Tshirt(Person component) { super(component); } @Override public void decorate() { System.out.println("T-shirt"); super.decorate(); } } public class Pants extends Clothes { public Pants(Person component) { super(component); } @Override public void decorate() { System.out.println("pants"); super.decorate(); } } public class Hat extends Clothes { public Hat(Person component) { super(component); } @Override public void decorate() { System.out.println("hat"); super.decorate(); } }
//测试类
public class Test { public static void main(String[] args) {
     //动态的装饰主类,可以选择性的调用装饰类,以及更改调用的顺序从而实现“动态” Person person
= new ConcretePerson(); Clothes tshirt = new Tshirt(person); Clothes pants = new Pants(tshirt); Clothes hat = new Hat(pants); hat.decorate(); } }

测试的结果为:

hat
pants
T-shirt
穿衣服的人

根据具体装饰类的创建顺序的改变,结果也会“动态”变化。

public class Test {
    public static void main(String[] args) {
        Person person = new ConcretePerson();
        Clothes pants = new Pants(person);
        Clothes tshirt = new Tshirt(pants);
        Clothes hat = new Hat(tshirt);

        hat.decorate();
    }
}

测试的结果为:

hat
T-shirt
pants
穿衣服的人

总结:当给一个类添加在某种特殊情况才需要的方法时,我们就可以使用装饰模式,避免使主类过于复杂,而且可以有选择的,有顺序的添加这些方法,使主类的主要逻辑和装饰功能区分开,从而简化主类。

原文地址:https://www.cnblogs.com/yimengyizhen/p/11080551.html