(a) Introduction to the model of entrustment
The delegate mode is one of the basic design patterns. delegate, which is to let another object help you do things.
Many other patterns, such as state mode, policy mode, and visitor pattern, are essentially delegate patterns in more special situations.
The delegate pattern allows us to use aggregations instead of inheritance, java-combinations better than inheritance.
The simplest Java delegate mode
Class Realprinter { void print () { System.out.println ("Real Printer");} } Class Printer { realprinter realprinter = new Realprinter (); public void print () { realprinter.print (); }}
/** * Simple Delegate mode * * @author Peter_wang * @create-time 2014-5-19 pm 5:39:42 */public class Delegationdemo { /** * @param args */public static void Main (string[] args) { Printer Printer = new Printer (); Printer.print (); }}
(ii) The delegation mode in Android
The Listerner event in Android is a delegate mode, such as a button click event. Let's simulate how the entire click event is using the delegate model.
/** * Analog Basic View * * @author Peter_wang * @create-time 2014-5-19 pm 5:03:55 */public Class View { private onclicklist Ener Monclicklistener; /** * Analog Click event */public void Clickevent () { if (monclicklistener! = null) { Monclicklistener.onclick (this); } } public void Setonclicklistener (Onclicklistener onclicklistener) { this.monclicklistener = Onclicklistener; } /** * Click event interface * * @author peter_wang * @create-time 2014-5-19 pm 5:05:45 */Public Interface Onclicklistener {public void OnClick (View v); }}
/** * Analog button * * @author Peter_wang * @create-time 2014-5-19 pm 5:17:57 */public class Button extends View {}
/** * Simulated basic Activity class * * @author Peter_wang * @create-time 2014-5-19 pm 5:20:38 */public class Activity {public STA tic void Main (string[] args) { activity activity = new activity (); Activity.oncreate (); } /** * Analog OnCreate method * /protected void OnCreate () { }}
/** * Commissioned Simulation page * * @author Peter_wang * @create-time 2014-5-19 pm 5:19:22 */public class delegationactivity extends A Ctivity implements Onclicklistener { private Button Mbutton; @Override protected void OnCreate () { super.oncreate (); Mbutton = new Button (); Mbutton.setonclicklistener (this); Analog Click event mbutton.clickevent (); } @Override public void OnClick (View v) { if (v = = Mbutton) { System.out.println ("OnClick () is callback!"); } }}