结构型之【装饰器模式】
定义:
装饰器模式(Decorator Pattern) 也称为包装模式(Wrapper Pattern) 是指在不改变原有对象的基础之上,将功能附加到对象上,提供了比继承更有弹性的替代方案(扩展原有对象的功能),属于结构型模式。装饰器模式的核心是功能扩展,使用装饰器模式可以透明且动态地扩展类的功能
一、Person接口
public interface Person { void GetRole(); void GetAge(); }
二、定义Father类并实现Person接口
public class Father implements Person { @Override public void GetRole() { System.out.println("role : father"); } @Override public void GetAge() { System.out.println("father age : 38 years"); } }
三、定义Mother类并实现Person接口
public class Mother implements Person { @Override public void GetRole() { System.out.println("role : Mother"); } @Override public void GetAge() { System.out.println("Mother Age : 30 years"); } }
四、定义Son类并实现Person接口
public class Son implements Person{ @Override public void GetRole() { System.out.println("son Age : 10 years"); } @Override public void GetAge() { System.out.println("role : son"); } }
五、定义PersonDecorator类并实现Person接口
public class PersonDecorator implements Person{ private Person person; public PersonDecorator(Person person) { this.person = person; } @Override public void GetAge() { person.GetAge(); } @Override public void GetRole() { person.GetRole(); } }
六、定义PersonMaleDecorator类并继承PersonDecorator
public class PersonMaleDecorator extends PersonDecorator { public PersonMaleDecorator(Person person) { super(person); } @Override public void GetAge() { super.GetAge(); this.SetAddFunction(); } @Override public void GetRole() { super.GetRole(); } // 附加方法 private void SetAddFunction() { System.out.println("this is a addfunction"); } }
七、测试
public class Main { public static void main(String[] args) { Mother mother=new Mother(); PersonMaleDecorator father=new PersonMaleDecorator(new Father()); PersonMaleDecorator son=new PersonMaleDecorator(new Son()); mother.GetRole(); mother.GetAge(); System.out.println("------------------------"); father.GetRole(); father.GetAge(); System.out.println("------------------------"); son.GetRole(); son.GetAge(); System.out.println("------------------------"); } }