代理设计模式与装饰设计模式

代理设计模式UML类图:  

 

代理设计模式是接口的应用之一,一个代理操作,一个真实操作。Runnable接口实现线程就是应用代理设计模式,如图:

以找中Jie租房为例的代理设计模式代码:

public class ProxyDemo {
	public static void main(String[] args) {
         //客户端不知道代理委托了另一个对象 RentHouse rent = new RentCompany(); rent.house("小心黑ZhongJie"); rent.house("租房贵"); } } interface RentHouse {//租房 public void house(String url); } class RealRent implements RentHouse { public void house(String url) { System.out.println("北京:" + url); } } class RentCompany implements RentHouse { private RentHouse r;//保存真正租房操作 public RentCompany() {
         //关系在编译时确定 this.r = new RealRent(); } public boolean check(String url) { if (url.contains("黑ZhongJie")) { System.out.println("不能租房"); return false; } return true; } public void house(String url) { if (this.check(url)) {// 通过检查了 this.r.house(url);//真实操作 } } }

  租房接口下有两个操作,一个真实租房操作,一个是中Jie公司。我们只需要租到房子就行,而租房的各种流程都交给中Jie公司处理,不用我们关心。即是说,代理操作处理复杂业务,真实操作处理核心业务,二者分开

装饰设计模式:

public class Client{
	public static void main(String[] args) {
          //客户端制定了装饰者需要装饰哪一个类
		Component c = new Decorator(new ConcreteDecorator());
		c.print("装饰");
		
	}
}
interface Component{
	public void print(String url);
}
//被装饰类 class ConcreteDecorator implements Component{ public void print(String url) { System.out.println("北京:" + url); } } //装饰类,可以为ConcreteDecorator类动态的添加一些功能 class Decorator implements Component{ private Component c; public Decorator(Component c) { this.c = c; } public void print(String url) {
         System.out.println("装饰前"); c.print();
         System.out.println("装饰后"); } }

输出结果:

装饰前
原始方法
装饰后

  

java io就是经典的装饰设计模式。

  PrintStream print = new PrintStream(new FileOutputStream());

  PrintStream操作的本质离不开OutputStream,只是将这个类的功能加强了

posted @ 2015-07-08 17:02  雨下个不停  阅读(170)  评论(0编辑  收藏  举报