前言:【模式總覽】——————————by xingoohtml
在不改變原來類的狀況下,進行擴展。ide
動態的給對象增長一個業務功能,就功能來講,比生成子類更方便。this
1 在不生成子類的狀況下,爲對象動態的添加某些操做。spa
2 處理一些能夠撤銷的職責。code
3 當不能使用生成子類來擴充時。component
Component 外部接口,用於定義外部調用的形式。提供默認的處理方法。htm
interface Component{ public void operation(); }
ConcreteComponent 具體的處理類,用於實現operation方法。對象
class ConcreteComponent implements Component{ @Override public void operation() { // TODO Auto-generated method stub System.out.println("ConcreteComponent operation()"); } }
Decorator 裝飾類,內部關聯一個component對象,調用其operation方法,並添加本身的業務操做。blog
class Decorator implements Component{ private Component component; @Override public void operation() { // TODO Auto-generated method stub System.out.println("before decorator!"); component.operation(); System.out.println("after decorator!"); } public Decorator() { // TODO Auto-generated constructor stub } public Decorator(Component component){ this.component = component; } }
1 package com.xingoo.decorator; 2 interface Component{ 3 public void operation(); 4 } 5 class ConcreteComponent implements Component{ 6 7 @Override 8 public void operation() { 9 // TODO Auto-generated method stub 10 System.out.println("ConcreteComponent operation()"); 11 } 12 13 } 14 class Decorator implements Component{ 15 private Component component; 16 @Override 17 public void operation() { 18 // TODO Auto-generated method stub 19 System.out.println("before decorator!"); 20 component.operation(); 21 System.out.println("after decorator!"); 22 } 23 public Decorator() { 24 // TODO Auto-generated constructor stub 25 } 26 public Decorator(Component component){ 27 this.component = component; 28 } 29 30 } 31 32 33 public class test { 34 public static void main(String[] args) { 35 Component component = new Decorator(new ConcreteComponent()); 36 component.operation(); 37 } 38 }
運行結果接口
before decorator! ConcreteComponent operation() after decorator!