代理模式

姓名:宁前程

学号:07770118

 

模式名称:代理模式

 

1.问题描述

生活场景:很多人想购买李宁牌衣服,然后纷纷跑到李宁公司总部去购买,不但买不到自己想要的衣服,还白白的跑了一趟。

 

设计目的:让用户不必非要跑到李宁公司总部去购买。

 

 

2.不假思索的思路

思路描述:很多人想购买李宁牌衣服,然后纷纷跑到李宁公司总部去购买。

 

类结构图:

缺点:这样的设计,为公司造成很多麻烦,也为自己造成很多麻烦。

 

代码:

 

首先定义一个能产生一批衣服的接口:

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午10:01:50

 */

public interface ClothingFactory {

    void productColthing();

}

 

“LiNingCompany”是一家能真正生产这一批服装的公司:

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午10:05:32

 */

public class LiNingCompany implements ClothingFactory {

    public void productColthing() {

       System.out.println("生产一批LiNing服装");

    }

}

 

顾客:

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午11:21:58

 */

public class Customer {

    public static void main(String[] args) {

       ClothingFactory cf = new LiNingCompany();

       cf.productColthing();

    }

}

 

 

3.归纳阶段:

思路描述:我们可以通过一个中介公司,由于中介公司帮他找厂家做这些衣服,当然中介公司要从中收取一定的中介费 。

类结构图:

 

代码:

首先定义一个能产生一批衣服的接口:

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午10:01:50

 */

public interface ClothingFactory {

    void productColthing();

}

 

“LiNingCompany”是一家能真正生产这一批服装的公司:

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午10:05:32

 */

public class LiNingCompany implements ClothingFactory {

    public void productColthing() {

       System.out.println("生产一批LiNing服装");

    }

}

 

“ProxyCompany”是一家专门帮助人介绍服装公司的中介公司,他需要收取一定的中介费。

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午10:08:01

 */

public class ProxyCompany implements ClothingFactory {

    private ClothingFactory cf;

    public ProxyCompany(ClothingFactory cf){

       this.cf = cf;

    }

    public void productColthing() {

           System.out.println("收取1000元中介费");

       cf.productColthing();

    }

}

 

 

设计体会:

这样的设计通过加一个代理来降低对象的使用复杂度,需要通过代理对象来间接操作目标对象,代理就在客户端和目标对象之间起到中介的作用。

 

4.验证阶段

思路描述:通过顾客去购买李宁衣服来实现代理模式。

 

代码:

顾客:

package com.lning.DaiLi;

/**

 * @author 老宁

 *2010-10-24上午11:21:58

 */

public class Customer {

    public static void main(String[] args) {

       ClothingFactory cf = new ProxyCompany(new LiNingCompany());

       cf.productColthing();

    }

}

 

运行这个程序,在控制台得到如下输出结果:

收取1000元中介费

生产出一批LiNing服装

5.抽象描述

思路描述:代理模式非常常用,大致的思想就是通过为对象加一个代理来降低对象的使用复杂度、或是提升对象使用的友好度、或是提高对象使用的效率。

 

类结构图:

posted @ 2010-12-01 21:28  天津城建学院软件工程  阅读(311)  评论(0编辑  收藏  举报