/*** Created by TigerChain* 代理人,我上场了,感觉像媒婆*/public class ProxyTigerChain implements ZhuimmWay {private XiaoMing xiaoMing ;public ProxyTigerChain(XiaoMing xiaoMing, MM mm){this.xiaoMing = xiaoMing ;xiaoMing.like(mm);}@Overridepublic void giveFlowers() {xiaoMing.giveFlowers();}@Overridepublic void writeLoveLetters() {xiaoMing.writeLoveLetters();}@Overridepublic void buyClothes() {xiaoMing.buyClothes();}@Overridepublic void doSomthing() {xiaoMing.doSomthing();}}
public class Test {public static void main(String args[]){// 主人公小明XiaoMing xiaoMing = new XiaoMing();// 要追的人小倩MM xiaoqian = new MM("小倩") ;// 小明委托我去帮他追小倩ProxyTigerChain proxyChain = new ProxyTigerChain(xiaoMing,xiaoqian) ;proxyChain.giveFlowers();proxyChain.writeLoveLetters();proxyChain.buyClothes();proxyChain.doSomthing();}}
上面的代码完美吗?完美个鸟鸟,试想把 Test 比做一个场景:比如是在 KTV,我靠,小明不是害羞吗?竟然也出现在 KTV 中「如果小明能当明看着你帮他追小倩,早就自己动手了」,所以按正常逻辑小明不应该出现在 KTV「Test 中」
/*** Created by TigerChain* 定义一个工厂类,这样就屏蔽了客户端对代理的感知*/public class ZhuimmFactory {public static ZhuimmWay getInstance(String name){return new ProxyTigerChain(new XiaoMing(),new MM(name)) ;}}
嘻嘻,不知不觉又用到以前学到的简单工厂模式了「学以致用,不错不错」,我们把代理事情都放在工厂中去做,这样客户端对代理是无感知的,这也符合程序开发的正常逻辑
public class Test {public static void main(String args[]){// 调用者不知道调用的是代理类还是真实类,这才是正常的逻辑呀ZhuimmWay zhuimmWay = ZhuimmFactory.getInstance("小倩") ;zhuimmWay.giveFlowers();zhuimmWay.writeLoveLetters();zhuimmWay.buyClothes();zhuimmWay.doSomthing();}}
想知道结局吗?很不幸,小倩也有点”白痴”,我提醒好多次是小明喜欢她「其实我最多是代理小明送花等这些事情,也就是说钱花小明的,美女我来追」,可是她最终还是看上我了「有点自恋」,所以以后追 MM 的时候,千万千万不要找代理「以上故事纯属虚构,如有雷同,那么小明以后就张点心吧」
2、真假美猴王
1、使用静态代理完成
六耳猕猴梦想简单的 UML
根据 UML 撸码
/*** Created 抽象类,去西天的条件*/public interface IToWest {//保护唐僧void baohuTangSeng() ;//降妖除魔void xiangYaoChuMo() ;//上天入地void shangTianRuDi() ;}
/*** Created by Tigerchain* 悟空*/public class SunWuKong implements IToWest{@Overridepublic void baohuTangSeng() {System.out.println("我孙悟空能 保护唐僧");}@Overridepublic void xiangYaoChuMo() {System.out.println("我孙悟空能 降妖除魔");}@Overridepublic void shangTianRuDi() {System.out.println("我孙悟空能 能上天入地");}}
package prxoy.monkeyking;/*** Created by Tigerchain* 悟空的代理六耳猕猴*/public class LiuErMiHou extends SunWuKong implements IToWest {@Overridepublic void baohuTangSeng() {super.baohuTangSeng();}@Overridepublic void xiangYaoChuMo() {super.xiangYaoChuMo();}@Overridepublic void shangTianRuDi() {super.shangTianRuDi();}}
/*** Created by TigerChain* 测试类 六耳 代理悟空*/public class Test {public static void main(String args[]){IToWest liuErMiHou = new LiuErMiHou() ;liuErMiHou.baohuTangSeng();liuErMiHou.xiangYaoChuMo();liuErMiHou.shangTianRuDi();System.out.println("我孙悟空能去得了西天");}}
- 【STM32】引脚配置—F1与F4系列
- 图论系列:图的表示
- 一年养50头猪赚多少钱,养50头母猪一年能挣多少钱
- 一、Java反射机制具体是什么
- 仙人掌怎么养成木质化
- 水培红掌怎么养才能开花
- 黄金香柳养殖方法和注意事项
- 番茄怎么种植
- 蔷薇有哪些病虫害,应如何防治
- 常绿灌木有哪些树种