To being, or not to Be:that is the question.
--"Hamlet"
Proxy mode, which provides a proxy for other objects to control access to this object.
On the code:
1 Package Cn.no4.proxy; 2 3 Public Interface Imakemoney {45 void Makemoney (); 6 }
1 Package Cn.no4.proxy;2 3 Public classProxy implements Imakemoney {4 5 Privateboss boss;6 7 PublicProxy () {8Boss =NewBoss ();9 }Ten One @Override A Public voidMakemoney () { -System. out. println ("on the surface is proxy doing things ..."); - Boss.makemoney (); the } - -}
1 Package Cn.no4.proxy;2 3 Public classBoss implements imakemoney{4 5 Private DoubleMoney ;6 7 8 Public DoubleGetmoney () {9 returnMoney ;Ten } One A - Public voidSetmoney (DoubleMoney ) { - This. Money =Money ; the } - - - @Override + Public voidMakemoney () { - +Money + =5000000; ASystem. out. println ("is actually behind the big boss dry, Big Boss got $"+Money ); at } - -}
Test class:
1 package cn.no4.proxy; 2 3 public class _test { 4 5 public static void main (string[] args) { 6 proxy proxy = new Proxy (); 7 Proxy.makemoney (); 8 } 9 }
The following changes the Makemoney method of the proxy class, which realizes the control of the Boss object access:
1 Package cn.no4.proxy.instance;2 3 Public classProxy implements Imakemoney {4 5 Privateboss boss;6 7 PublicProxy () {8Boss =NewBoss ();9 }Ten One @Override A Public voidMakemoney (DoubleMoney ) { -System. out. println ("on the surface is proxy doing things ..."); - //The following code implements control of boss access the if(Money <5000000.0) { -System. out. println ("too little money to send beggars! "); -}Else{ - Boss.makemoney (money); + } - } + A}
Test class:
1 Package cn.no4.proxy.instance;2 3 Public class_test {4 5 Public Static voidMain (string[] args) {6Proxy proxy =NewProxy ();7Proxy.makemoney (1);8Proxy.makemoney (5000000);9 }Ten}
Proxy.makemoney (1); Unable to access the Boss object because 1 bucks is too little for the boss.
Proxy.makemoney (5000000); This gives you access to the Boss object and executes the boss's Makemoney method.
Java Learning notes--design pattern four. Proxy mode