java设计模式之代理模式

代理模式:为其他对象提供一个代理对象,并由代理对象控制对原对象的访问。
直接上经典代码

//代理模式

//定义一种类型的女人,这类女人都有这种特性,所以用接口
interface KindWomen{
	void makeEyesWithMan();
	void happyWithMan();
}

//潘金莲
class PanJinLian implements KindWomen{
	public void makeEyesWithMan(){
		System.out.println("潘金莲抛媚眼。。。");
	}
	public void happyWithMan(){
		System.out.println("潘金莲和男人。。。");
	}
}

//丑陋的王婆
class WangPo implements KindWomen{
	private KindWomen kindWomen;
	public WangPo(){
		//默认是潘金莲的代理
		this.kindWomen = new PanJinLian();
	}
	public WangPo(KindWomen kindWomen){
		//也可以是这类女人中的任何一个的代理
		this.kindWomen = kindWomen;
	}
	public void makeEyesWithMan(){
		//年纪大了,没人看她抛媚眼
		this.kindWomen.makeEyesWithMan();
	}
	public void happyWithMan(){
		//自己老了,没精力了,但可以让年轻的代替
		this.kindWomen.happyWithMan();
	}
}

//贾氏
class JiaShi implements KindWomen{
	public void makeEyesWithMan(){
		System.out.println("贾氏抛媚眼。。。");
	}
	public void happyWithMan(){
		System.out.println("贾氏和男人。。。");
	}
}

//西门大官人出场
class XiMenQing{
	public static void main(String[] args){
		//把王婆叫出来
		WangPo wp = new WangPo();
		//表面是王婆在做,其实是潘金莲
		wp.makeEyesWithMan();
		wp.happyWithMan();
		
		//西门庆又去勾引贾氏
		wp= new WangPo(new JiaShi());
		wp.makeEyesWithMan();
		wp.happyWithMan();
	}
}

运行结果:
潘金莲抛媚眼。。。
潘金莲和男人。。。
贾氏抛媚眼。。。
贾氏和男人。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值