package com.DesignPattern.Structural.Decorator;
public interface Component {
public void operation();
}
package com.DesignPattern.Structural.Decorator;
public class ConcreteComponent implements Component {
@Override
public void operation() {
// 业务代码
System.out.println("concreteComponent opration");
}
}
package com.DesignPattern.Structural.Decorator;
public abstract class Decorator implements Component {
private Component component=null;
public Decorator(Component component){
this.component=component;
}
@Override
public void operation() {
this.component.operation();
}
}
package com.DesignPattern.Structural.Decorator;
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
//自己定义的方法
private void method(){
System.out.println("add decorator method");
}
//重写operation方法
public void operation(){
this.method();
super.operation();
}
}
package com.DesignPattern.Structural.Decorator;
public class Client {
public static void main(String[] args){
Component component=new ConcreteComponent();
//进行装饰
component=new ConcreteDecorator(component);
component.operation();
}
}
package com.DesignPattern.Structural.Decorator;
//汽车接口
public interface Car {
// 车的装配
public void show();
}
package com.DesignPattern.Structural.Decorator;
//奔驰车(裸车,需要装饰)
public class Benz implements Car {
@Override
public void show() {
System.out.println("Benz default color is black");
}
}
package com.DesignPattern.Structural.Decorator;
//汽车装饰(抽象装饰)
public abstract class CarDecorator implements Car {
private Car car = null;
public CarDecorator(Car car) {
this.car = car;
}
@Override
public void show() {
this.car.show();
}
}
package com.DesignPattern.Structural.Decorator;
//具体汽车修饰
public class ConcreteCarDecorator extends CarDecorator {
public ConcreteCarDecorator(Car car) {
super(car);
}
// 给车彩绘
private void print() {
System.out.println("print on car");
}
// 给车安装GPS
private void setGps() {
System.out.println("install GPS");
}
// 重写show()方法
public void show() {
super.show();
this.print();
this.setGps();
}
}
package com.DesignPattern.Structural.Decorator;
public class ClientDemo {
public static void main(String[] args) {
Car car = new Benz();
// 对奔驰车进行装饰
CarDecorator cd = new ConcreteCarDecorator(car);
cd.show();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载|Copyright ©2011-2015,Supernatural, All Rights Reserved.
DesignPattern_Java:Decorator Pattern
原文地址:http://blog.csdn.net/williamfan21c/article/details/48035925