public class 装饰器模式 { public static void main(String[] args) { //第一种写法 Person person=new Student("张三"); person.Operation(); System.out.println(); person =new DecoratorA(person); person.Operation(); System.out.println(); person =new DecoratorB(person); person.Operation(); System.out.println(); //第二种写法 对象链 Person lisi=new DecoratorA(new Student("李四")); lisi.Operation(); } } abstract class Person{ protected String name; public abstract void Operation(); } class Student extends Person{ Student(String name) { this.name=name; } @Override public void Operation() { System.out.print(name); } } abstract class Decorator extends Person{ protected Person person; } class DecoratorA extends Decorator{ public DecoratorA(Person person) { this.person=person; } @Override public void Operation() { person.Operation(); System.out.print("写作业"); } } class DecoratorB extends Decorator{ public DecoratorB(Person person) { this.person=person; } @Override public void Operation() { person.Operation(); System.out.println("考满分"); } }
运行结果
标签:Person,软件设计,System,模式,public,person,Operation,装饰,out From: https://www.cnblogs.com/cinan/p/17798792.html