android深入之设计模式(1)委托模式

android深入之设计模式(一)委托模式

(一)委托模式简介

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

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

委托模式使得我们可以用聚合来替代继承,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!");
        }
    }

}



2楼u0108500273小时前
简洁是智慧的灵魂
1楼u0108500273小时前
委托跟代理有什么不一样nie