一委托模式简介 委托模式是基本的设计模式之一委托,即是让另一个对象帮你做事情 许多其他的模式,如状态模式、策略模式、访问者模式本质上是在更特殊的场合采用了委托模式 委托模式使得我们可以用聚合

(一)委托模式简介

委托模式是基本的设计模式之一。委托,即是让另一个对象帮你做事情。

许多其他的模式,如状态模式、策略模式、访问者模式本质上是在更特殊的场合采用了委托模式。

委托模式使得我们可以用聚合来替代继承,java-组合优于继承。

最简单的java委托模式

class RealPrinter {
    void print() {
        System.out.println("real printer");
    }
 }

class Printer {
     RealPrinter realPrinter = new RealPrinter();

     public void print() {
        realPrinter.print();
     }
}
/**
 * 简单委托模式
 * 
 * @author peter_wang
 * @create-time 2014-5-19 下午5:39:42
 */
public class DelegationDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print();
    }

}

(二)android中的委托模式

android中的listerner事件即是委托模式,比如Button点击事件。我们来模拟整个点击事件是如何运用委托模式的。

/** * 模拟基本View * * @author peter_wang * @create-time 2014-5-19 下午5:03:55 */ public class View { private OnClickListener mOnClickListener; /** * 模拟点击事件 */ public void clickEvent() { if (mOnClickListener != null) { mOnClickListener.onClick(this); } } public void setonClickListener(OnClickListener onClickListener) { this.mOnClickListener = onClickListener; } /** * 点击事件接口 * * @author peter_wang * @create-time 2014-5-19 下午5:05:45 */ public interface OnClickListener { public void onClick(View v); } }

/**
 * 模拟按钮
 * 
 * @author peter_wang
 * @create-time 2014-5-19 下午5:17:57
 */
public class Button
    extends View {

}

/** * 模拟基本Activity类 * * @author peter_wang * @create-time 2014-5-19 下午5:20:38 */ public class Activity { public static void main(String[] args) { Activity activity = new Activity(); activity.onCreate(); } /** * 模拟OnCreate方法 */ protected void onCreate() { } }
/** * 委托模拟页面 * * @author peter_wang * @create-time 2014-5-19 下午5:19:22 */ public class DelegationActivity extends Activity implements OnClickListener { private Button mButton; @Override protected void onCreate() { super.onCreate(); mButton = new Button(); mButton.setonClickListener(this); // 模拟点击事件 mButton.clickEvent(); } @Override public void onClick(View v) { if (v == mButton) { System.out.println("onClick() is callback!"); } } }

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...