JAVA 装饰者模式
public interface Person { void introduce(); }
public class Student implements Person { public Student() { // TODO Auto-generated constructor stub } public void introduce() { System.out.println("我要去听课"); } }
public class Teacher implements Person { public Teacher() { // TODO Auto-generated constructor stub } @Override public void introduce() { // TODO Auto-generated method stub System.out.println("我要去讲课"); } }
实现方法
public class Introduce implements Person { Person person; public Introduce() { // TODO Auto-generated constructor stub } public Introduce(Person person) { this.person = person; } @Override public void introduce() { // TODO Auto-generated method stub System.out.println("大家好"); person.introduce(); } }
主函数
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub Student student = new Student(); Introduce sIntroduce = new Introduce(student); sIntroduce.introduce(); Teacher teacher = new Teacher(); Introduce tIntroduce = new Introduce(teacher); tIntroduce.introduce(); } }
运行结果
大家好
我要去听课
大家好
我要去讲课