廣告

2015年4月27日 星期一

[design pattern] [java] Decorator pattern

這種模式讓你不用修改現有的interface,
並且對其新添加功能,

重點在於Employee.java的第七行,
除了複寫walk的method,還添加了
run的method在裡面.




Human.java
package com.test.decoratorpattern;

public interface Human {

 void walk(String msg);
}




Man.java
package com.test.decoratorpattern;

public class Man implements Human{

 @Override
 public void walk(String msg) {
  System.out.println("class is Man , "+msg);
 }

}




ManDecorator.java
package com.test.decoratorpattern;

public class ManDecorator implements Human {

 protected Human decoratedHuman;

 public ManDecorator(Human decoratedHuman) {
  this.decoratedHuman = decoratedHuman;
 }

 public void walk(String msg) {
  decoratedHuman.walk("class is ManDecorator:"+msg);
 }

}




Employee.java
package com.test.decoratorpattern;

public class Employee extends ManDecorator {

 public Employee(Human decoratedHuman) {
  super(decoratedHuman);
  // TODO Auto-generated constructor stub
 }

 @Override
 public void walk(String msg) {
  decoratedHuman.walk(msg);
  run(decoratedHuman);
 }

 private void run(Human decoratedHuman) {
  System.out.println("class is Employee: Run");
 }

}




testDecorator.java
package com.test.decoratorpattern;

public class testDecorator {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  Human man = new Man();
  man.walk(" man ");
  
  Human employee = new Employee(new Man());
  employee.walk(" employee ");

        
 }

}




Console
class is Man ,  man 
class is Man ,  employee 
class is Employee: Run

沒有留言:

張貼留言