java设计模式之代理模式

    xiaoxiao2022-06-28  22

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

    //代理模式 //定义一种类型的女人,这类女人都有这种特性,所以用接口 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(); } }

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

    转载请注明原文地址: https://ju.6miu.com/read-1124442.html

    最新回复(0)