DesignPatterns->装饰器模式

package com.zhiru;

/*
 * 装饰器模式
 * 实现动态的为对象添加功能
 * 是从一个对象外部给一个对象添加功能。
 * 基于对象组合的方式给对象添加功能
 * 组成要素:Component,ConcreteComponent,Decorator,ConcreteDecorator1,ConcreteDecorator2,...
 */
//http://blog.163.com/michael_yu/blog/static/173853371201010365749187/

//Component
//学生接口
abstract class Student {
	public abstract void student();
}

// concretecomponent
// 具体的学生接口
class GoodStudent extends Student {

	@Override
	public void student() {
		// TODO Auto-generated method stub
		System.out.println("good student");
	}

}

// Decorator
// 学生接口装饰器,对学生抽象类进行组合.
class DecoratorStudent extends Student {
	private Student stu;

	public DecoratorStudent(Student stu) {
		this.stu = stu;
	}

	@Override
	public void student() {
		// TODO Auto-generated method stub
		stu.student();
	}

}

// ConcreteDecorator class
// 三好学生
class ThreeGoodStudent extends DecoratorStudent {

	public ThreeGoodStudent(Student stu) {
		super(stu);
	}

	public void student() {
		super.student();
		System.out.println("three good student");
	}
}

// 乐于助人的学生
class WarmHeartStudent extends DecoratorStudent {

	public WarmHeartStudent(Student stu) {
		super(stu);
		// TODO Auto-generated constructor stub
	}

	public void student() {
		super.student();
		System.out.println("warm hearted student");
	}
}

// 擅长编程的学生
class BeginningAbilityStudent extends DecoratorStudent {

	public BeginningAbilityStudent(Student stu) {
		super(stu);
		// TODO Auto-generated constructor stub
	}

	public void student() {
		super.student();
		System.out.println("be good at programming student");
	}
}

public class DecoratorPattern {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 擅长编程的,三好好学生
		new BeginningAbilityStudent(new ThreeGoodStudent(new GoodStudent()))
				.student();
		// 热心,善于编程,三好,好学生。
		new WarmHeartStudent(new BeginningAbilityStudent(new ThreeGoodStudent(
				new GoodStudent()))).student();
	}

}
/*
 * good student three good student be good at programming student 
 * good student
 * three good student be good at programming student warm hearted student
 */
参考博客:http://blog.163.com/michael_yu/blog/static/173853371201010365749187/

你可能感兴趣的:(设计模式,装饰器设计模式)