android开发中常见的设计模式 -尊龙游戏旗舰厅官网
对于开发人员来说,设计模式有时候就是一道坎,但是设计模式又非常有用,过了这道坎,它可以让你水平提高一个档次。而在android开发中,必要的了解一些设计模式又是非常有必要的。对于想系统的学习设计模式的同学,这里推荐2本书。一本是head first系列的head hirst design pattern,英文好的可以看英文,可以多读几遍。另外一本是大话设计模式。
单例模式
首先了解一些单例模式的概念。
确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
这样做有以下几个优点
- 对于那些比较耗内存的类,只实例化一次可以大大提高性能,尤其是在移动开发中。
- 保持程序运行的时候该中始终只有一个实例存在内存中
其实单例有很多种实现方式,但是个人比较倾向于其中1种。可以见单例模式
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class singleton { private static volatile singleton instance = null; private singleton(){ } public static singleton getinstance() { if (instance == null) { synchronized (singleton.class) { if (instance == null) { instance = new singleton(); } } } return instance; } } |
要保证单例,需要做一下几步
- 必须防止外部可以调用构造函数进行实例化,因此构造函数必须私有化。
- 必须定义一个静态函数获得该单例
- 单例使用volatile修饰
- 使用synchronized 进行同步处理,并且双重判断是否为null,我们看到synchronized (singleton.class)里面又进行了是否为null的判断,这是因为一个线程进入了该代码,如果另一个线程在等待,这时候前一个线程创建了一个实例出来完毕后,另一个线程获得锁进入该同步代码,实例已经存在,没必要再次创建,因此这个判断是否是null还是必须的。
至于单例的并发测试,可以使用countdownlatch,使用await()等待锁释放,使用countdown()释放锁从而达到并发的效果。可以见下面的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static void main(string[] args) { final countdownlatch latch = new countdownlatch(1); int threadcount = 1000; for (int i = 0; i < threadcount; i ) { new thread() { |
看看打印出来的hashcode会不会出现不一样即可,理论上是全部都一样的。
而在android中,很多地方用到了单例。
比如android-universal-image-loader中的单例
1 2 3 4 5 6 7 8 9 10 11 12 | private volatile static imageloader instance; /** returns singleton class instance */ public static imageloader getinstance() { if (instance == null) { synchronized (imageloader.class) { if (instance == null) { instance = new imageloader(); } } } return instance; } |
比如eventbus中的单例
1 2 3 4 5 6 7 8 9 10 11 | private static volatile eventbus defaultinstance; public static eventbus getdefault() { if (defaultinstance == null) { synchronized (eventbus.class) { if (defaultinstance == null) { defaultinstance = new eventbus(); } } } return defaultinstance; } |
上面的单例都是比较规规矩矩的,当然实际上有很多单例都是变了一个样子,单本质还是单例。
如inputmethodmanager 中的单例
1 2 3 4 5 6 7 8 9 10 11 | static inputmethodmanager sinstance; public static inputmethodmanager getinstance() { synchronized (inputmethodmanager.class) { if (sinstance == null) { ibinder b = servicemanager.getservice(context.input_method_service); iinputmethodmanager service = iinputmethodmanager.stub.asinterface(b); sinstance = new inputmethodmanager(service, looper.getmainlooper()); } return sinstance; } } |
accessibilitymanager 中的单例,看代码这么长,其实就是进行了一些判断,还是一个单例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | private static accessibilitymanager sinstance; public static accessibilitymanager getinstance(context context) { synchronized (sinstancesync) { if (sinstance == null) { final int userid; if (binder.getcallinguid() == process.system_uid || context.checkcallingorselfpermission( manifest.permission.interact_across_users) == packagemanager.permission_granted || context.checkcallingorselfpermission( manifest.permission.interact_across_users_full) == packagemanager.permission_granted) { userid = userhandle.user_current; } else { userid = userhandle.myuserid(); } ibinder ibinder = servicemanager.getservice(context.accessibility_service); iaccessibilitymanager service = iaccessibilitymanager.stub.asinterface(ibinder); sinstance = new accessibilitymanager(context, service, userid); } } return sinstance; } |
当然单例还有很多种写法,比如恶汉式,有兴趣的自己去了解就好了。
最后,我们应用一下单例模式。典型的一个应用就是管理我们的activity,下面这个可以作为一个工具类,代码也很简单,也不做什么解释了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public class activitymanager { private static volatile activitymanager instance; private stack private activitymanager(){ } public static activitymanager getinstance(){ if (instance == null) { synchronized (activitymanager.class) { if (instance == null) { instance = new activitymanager(); } } return instance; } public void addacticity(activity act){ mactivitystack.push(act); } public void removeactivity(activity act){ mactivitystack.remove(act); } public void killmyprocess(){ int ncount = mactivitystack.size(); for (int i = ncount - 1; i >= 0; i--) { activity activity = mactivitystack.get(i); activity.finish(); } mactivitystack.clear(); android.os.process.killprocess(android.os.process.mypid()); } } |
这个类可以在开源中国的几个客户端中找到类似的源码
-
git@osc中的appmanager
-
android-app中的appmanager
以上两个类是一样的,没区别。
build模式
了解了单例模式,接下来介绍另一个常见的模式——builder模式。
那么什么是builder模式呢。你通过搜索,会发现大部分网上的定义都是
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
但是看完这个定义,并没有什么卵用,你依然不知道什么是builder设计模式。在此个人的态度是学习设计模式这种东西,不要过度在意其定义,定义往往是比较抽象的,学习它最好的例子就是通过样例代码。
我们通过一个例子来引出builder模式。假设有一个person类,我们通过该person类来构建一大批人,这个person类里有很多属性,最常见的比如name,age,weight,height等等,并且我们允许这些值不被设置,也就是允许为null,该类的定义如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public class person { private string name; private int age; private double height; private double weight; public string getname() { return name; } public void setname(string name) { this.name = name; } public int getage() { return age; } public void setage(int age) { this.age = age; } public double getheight() { return height; } public void setheight(double height) { this.height = height; } public double getweight() { return weight; } public void setweight(double weight) { this.weight = weight; } } |
然后我们为了方便可能会定义一个构造方法。
1 2 3 4 5 6 | public person(string name, int age, double height, double weight) { this.name = name; this.age = age; this.height = height; this.weight = weight; } |
或许为了方便new对象,你还会定义一个空的构造方法
1 2 | public person() { } |
甚至有时候你很懒,只想传部分参数,你还会定义如下类似的构造方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public person(string name) { this.name = name; } public person(string name, int age) { this.name = name; this.age = age; } public person(string name, int age, double height) { this.name = name; this.age = age; this.height = height; } |
于是你就可以这样创建各个需要的对象
1 2 3 4 5 | person p1=new person(); person p2=new person("张三"); person p3=new person("李四",18); person p4=new person("王五",21,180); person p5=new person("赵六",17,170,65.4); |
可以想象一下这样创建的坏处,最直观的就是四个参数的构造函数的最后面的两个参数到底是什么意思,可读性不怎么好,如果不点击看源码,鬼知道哪个是weight哪个是height。还有一个问题就是当有很多参数时,编写这个构造函数就会显得异常麻烦,这时候如果换一个角度,试试builder模式,你会发现代码的可读性一下子就上去了。
我们给person增加一个静态内部类builder类,并修改person类的构造函数,代码如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | public class person { private string name; private int age; private double height; private double weight; privateperson(builder builder) { this.name=builder.name; this.age=builder.age; this.height=builder.height; this.weight=builder.weight; } public string getname() { return name; } public void setname(string name) { this.name = name; } public int getage() { return age; } public void setage(int age) { this.age = age; } public double getheight() { return height; } public void setheight(double height) { this.height = height; } public double getweight() { return weight; } public void setweight(double weight) { this.weight = weight; } static class builder{ private string name; private int age; private double height; private double weight; public builder name(string name){ this.name=name; return this; } public builder age(int age){ this.age=age; return this; } public builder height(double height){ this.height=height; return this; } public builder weight(double weight){ this.weight=weight; return this; } public person build(){ return new person(this); } } } |
从上面的代码中我们可以看到,我们在builder类里定义了一份与person类一模一样的变量,通过一系列的成员函数进行设置属性值,但是返回值都是this,也就是都是builder对象,最后提供了一个build函数用于创建person对象,返回的是person对象,对应的构造函数在person类中进行定义,也就是构造函数的入参是builder对象,然后依次对自己的成员变量进行赋值,对应的值都是builder对象中的值。此外builder类中的成员函数返回builder对象自身的另一个作用就是让它支持链式调用,使代码可读性大大增强。
于是我们就可以这样创建person类。
1 2 3 4 5 6 7 | person.builder builder=new person.builder(); person person=builder .name("张三") .age(18) .height(178.5) .weight(67.4) .build(); |
有没有觉得创建过程一下子就变得那么清晰了。对应的值是什么属性一目了然,可读性大大增强。
其实在android中, builder模式也是被大量的运用。比如常见的对话框的创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | alertdialog.builder builder=new alertdialog.builder(this); alertdialog dialog=builder.settitle("标题") .seticon(android.r.drawable.ic_dialog_alert) .setview(r.layout.myview) .setpositivebutton(r.string.positive, new dialoginterface.onclicklistener() { |
其实在java中有两个常见的类也是builder模式,那就是stringbuilder和stringbuffer,只不过其实现过程简化了一点罢了。
我们再找找builder模式在各个框架中的应用。
如gson中的gsonbuilder,代码太长了,就不贴了,有兴趣自己去看源码,这里只贴出其builder的使用方法。
1 2 3 4 5 6 | gsonbuilder builder=new gsonbuilder(); gson gson=builder.setprettyprinting() .disablehtmlescaping() .generatenonexecutablejson() .serializenulls() .create(); |
还有eventbus中也有一个builder,只不过这个builder外部访问不到而已,因为它的构造函数不是public的,但是你可以在eventbus这个类中看到他的应用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public static eventbusbuilder builder() { return new eventbusbuilder(); } public eventbus() { this(default_builder); } eventbus(eventbusbuilder builder) { subscriptionsbyeventtype = new hashmap typesbysubscriber = new hashmap |
再看看著名的网络请求框架okhttp
1 2 3 4 5 | request.builder builder=new request.builder(); request request=builder.addheader("","") . .post(body) .build(); |
除了request外,response也是通过builder模式创建的。贴一下response的构造函数
1 2 3 4 5 6 7 8 9 10 11 12 | private response(builder builder) { this.request = builder.request; this.protocol = builder.protocol; this.code = builder.code; this.message = builder.message; this.handshake = builder.handshake; this.headers = builder.headers.build(); this.body = builder.body; this.networkresponse = builder.networkresponse; this.cacheresponse = builder.cacheresponse; this.priorresponse = builder.priorresponse; } |
可见各大框架中大量的运用了builder模式。最后总结一下
- 定义一个静态内部类builder,内部的成员变量和外部类一样
- builder类通过一系列的方法用于成员变量的赋值,并返回当前对象本身(this)
- builder类提供一个build方法或者create方法用于创建对应的外部类,该方法内部调用了外部类的一个私有构造函数,该构造函数的参数就是内部类builder
- 外部类提供一个私有构造函数供内部类调用,在该构造函数中完成成员变量的赋值,取值为builder对象中对应的值
观察者模式
前面介绍了单例模式和builder模式,这部分着重介绍一下观察者模式。先看下这个模式的定义。
定义对象间的一种一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都能得到通知并被自动更新
还是那句话,定义往往是抽象的,要深刻的理解定义,你需要自己动手实践一下。
先来讲几个情景。
-
情景1
有一种短信服务,比如天气预报服务,一旦你订阅该服务,你只需按月付费,付完费后,每天一旦有天气信息更新,它就会及时向你发送最新的天气信息。
-
情景2
杂志的订阅,你只需向邮局订阅杂志,缴纳一定的费用,当有新的杂志时,邮局会自动将杂志送至你预留的地址。
观察上面两个情景,有一个共同点,就是我们无需每时每刻关注尊龙游戏旗舰厅官网感兴趣的东西,我们只需做的就是订阅感兴趣的事物,比如天气预报服务,杂志等,一旦我们订阅的事物发生变化,比如有新的天气预报信息,新的杂志等,被订阅的事物就会即时通知到订阅者,即我们。而这些被订阅的事物可以拥有多个订阅者,也就是一对多的关系。当然,严格意义上讲,这个一对多可以包含一对一,因为一对一是一对多的特例,没有特殊说明,本文的一对多包含了一对一。
现在你反过头来看看观察者模式的定义,你是不是豁然开朗了。
然后我们看一下观察者模式的几个重要组成。
- 观察者,我们称它为observer,有时候我们也称它为订阅者,即subscriber
- 被观察者,我们称它为observable,即可以被观察的东西,有时候还会称之为主题,即subject
至于观察者模式的具体实现,这里带带大家实现一下场景一,其实java中提供了observable类和observer接口供我们快速的实现该模式,但是为了加深印象,我们不使用这两个类。
场景1中我们感兴趣的事情是天气预报,于是,我们应该定义一个weather实体类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class weather { private string description; public weather(string description) { this.description = description; } public string getdescription() { return description; } public void setdescription(string description) { this.description = description; } |
然后定义我们的被观察者,我们想要这个被观察者能够通用,将其定义成泛型。内部应该暴露register和unregister方法供观察者订阅和取消订阅,至于观察者的保存,直接用arraylist即可,此外,当有主题内容发送改变时,会即时通知观察者做出反应,因此应该暴露一个notifyobservers方法,以上方法的具体实现见如下代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class observable<t> { list public void register(observer if (observer == null) { throw new nullpointerexception("observer == null"); } synchronized (this) { if (!mobservers.contains(observer)) mobservers.add(observer); } } public synchronized void unregister(observer mobservers.remove(observer); } public void notifyobservers(t data) { for (observer observer.onupdate(this, data); } } } |
而我们的观察者,只需要实现一个观察者的接口observer,该接口也是泛型的。其定义如下。
1 2 3 | public interface observer<t> { void onupdate(observable } |
一旦订阅的主题发送变换就会回调该接口。
我们来使用一下,我们定义了一个天气变换的主题,也就是被观察者,还有两个观察者观察天气变换,一旦变换了,就打印出天气信息,注意一定要调用被观察者的register进行注册,否则会收不到变换信息。而一旦不敢兴趣了,直接调用unregister方法进行取消注册即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class main { public static void main(string [] args){ observable observer |
最后的输出结果也是没有什么问题的,如下
观察者1:weather{description=’晴转多云’}
观察者2:weather{description=’晴转多云’}
观察者1:weather{description=’多云转阴’}
观察者2:weather{description=’多云转阴’}
观察者2:weather{description=’台风’}
接下来我们看看观察者模式在android中的应用。我们从最简单的开始。还记得我们为一个button设置点击事件的代码吗。
1 2 3 4 5 6 7 | button btn=new button(this); btn.setonclicklistener(new view.onclicklistener() { |
其实严格意义上讲,这个最多算是回调,但是我们可以将其看成是一对一的观察者模式,即只有一个观察者。
其实只要是set系列的设置监听器的方法最多都只能算回调,但是有一些监听器式add进去的,这种就是观察者模式了,比如recyclerview中的addonscrolllistener方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | private list public void addonscrolllistener(onscrolllistener listener) { if (mscrolllisteners == null) { mscrolllisteners = new arraylist } mscrolllisteners.add(listener); } public void removeonscrolllistener(onscrolllistener listener) { if (mscrolllisteners != null) { mscrolllisteners.remove(listener); } } public void clearonscrolllisteners() { if (mscrolllisteners != null) { mscrolllisteners.clear(); } } |
然后有滚动事件时便会触发观察者进行方法回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public abstract static class onscrolllistener { public void onscrollstatechanged(recyclerview recyclerview, int newstate){} public void onscrolled(recyclerview recyclerview, int dx, int dy){} } void dispatchonscrolled(int hresult, int vresult) { //... if (mscrolllisteners != null) { for (int i = mscrolllisteners.size() - 1; i >= 0; i--) { mscrolllisteners.get(i).onscrolled(this, hresult, vresult); } } } void dispatchonscrollstatechanged(int state) { //... if (mscrolllisteners != null) { for (int i = mscrolllisteners.size() - 1; i >= 0; i--) { mscrolllisteners.get(i).onscrollstatechanged(this, state); } } } |
类似的方法很多很多,都是add监听器系列的方法,这里也不再举例。
还有一个地方就是android的广播机制,其本质也是观察者模式,这里为了简单方便,直接拿本地广播的代码说明,即localbroadcastmanager。
我们平时使用本地广播主要就是下面四个方法
1 2 3 4 | localbroadcastmanager localbroadcastmanager=localbroadcastmanager.getinstance(this); localbroadcastmanager.registerreceiver(broadcastreceiver receiver, intentfilter filter); localbroadcastmanager.unregisterreceiver(broadcastreceiver receiver); localbroadcastmanager.sendbroadcast(intent intent) |
调用registerreceiver方法注册广播,调用unregisterreceiver方法取消注册,之后直接使用sendbroadcast发送广播,发送广播之后,注册的广播会收到对应的广播信息,这就是典型的观察者模式。具体的源代码这里也不贴。
android系统中的观察者模式还有很多很多,有兴趣的自己去挖掘,接下来我们看一下一些开源框架中的观察者模式。一说到开源框架,你首先想到的应该是eventbus。没错,eventbus也是基于观察者模式的。
观察者模式的三个典型方法它都具有,即注册,取消注册,发送事件
1 2 3 4 | eventbus.getdefault().register(object subscriber); eventbus.getdefault().unregister(object subscriber); eventbus.getdefault().post(object event); |
内部源码也不展开了。接下来看一下重量级的库,它就是rxjava,由于学习曲线的陡峭,这个库让很多人望而止步。
创建一个被观察者
1 2 3 4 5 6 7 8 9 | observable new observable.onsubscribe |
创建一个观察者,也就是订阅者
1 2 3 4 5 6 7 8 9 10 | subscriber |
观察者进行事件的订阅
1 | myobservable.subscribe(mysubscriber); |
具体源码也不展开,不过rxjava这个开源库的源码个人还是建议很值得去看一看的。
总之,在android中观察者模式还是被用得很频繁的。
原型模式
这部分介绍的模式其实很简单,即原型模式,按照惯例,先看定义。
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
这是什么鬼哦,本宝宝看不懂!不必过度在意这些定义,自己心里明白就ok了。没代码你说个jb。
首先我们定义一个person类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | public class person{ private string name; private int age; private double height; private double weight; public person(){ } public string getname() { return name; } public void setname(string name) { this.name = name; } public int getage() { return age; } public void setage(int age) { this.age = age; } public double getheight() { return height; } public void setheight(double height) { this.height = height; } public double getweight() { return weight; } public void setweight(double weight) { this.weight = weight; } |
要实现原型模式,只需要按照下面的几个步骤去实现即可。
- 实现cloneable接口
1 2 3 | public class person implements cloneable{ } |
- 重写object的clone方法
1 2 3 4 | @override public object clone(){ return null; } |
- 实现clone方法中的拷贝逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @override public object clone(){ person person=null; try { person=(person)super.clone(); person.name=this.name; person.weight=this.weight; person.height=this.height; person.age=this.age; } catch (clonenotsupportedexception e) { e.printstacktrace(); } return person; } |
测试一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class main { public static void main(string [] args){ person p=new person(); p.setage(18); p.setname("张三"); p.setheight(178); p.setweight(65); system.out.println(p); person p1= (person) p.clone(); system.out.println(p1); p1.setname("李四"); system.out.println(p); system.out.println(p1); } } |
输出结果如下
person{name=’张三’, age=18, height=178.0, weight=65.0}
person{name=’张三’, age=18, height=178.0, weight=65.0}
person{name=’张三’, age=18, height=178.0, weight=65.0}
person{name=’李四’, age=18, height=178.0, weight=65.0}
试想一下,两个不同的人,除了姓名不一样,其他三个属性都一样,用原型模式进行拷贝就会显得异常简单,这也是原型模式的应用场景之一。
一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时,可以考虑使用原型模式拷贝多个对象供调用者使用,即保护性拷贝。
但是假设person类里还有一个属性叫兴趣爱好,是一个list集合,就像这样子
1 2 3 4 5 6 7 8 9 | private arraylist public arraylist return hobbies; } public void sethobbies(arraylist this.hobbies = hobbies; } |
在进行拷贝的时候要格外注意,如果你直接按之前的代码那样拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @override public object clone(){ person person=null; try { person=(person)super.clone(); person.name=this.name; person.weight=this.weight; person.height=this.height; person.age=this.age; person.hobbies=this.hobbies; } catch (clonenotsupportedexception e) { e.printstacktrace(); } return person; } |
会带来一个问题
使用测试代码进行测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class main { public static void main(string [] args){ person p=new person(); p.setage(18); p.setname("张三"); p.setheight(178); p.setweight(65); arraylist hobbies.add("篮球"); hobbies.add("编程"); hobbies.add("长跑"); p.sethobbies(hobbies); system.out.println(p); person p1= (person) p.clone(); system.out.println(p1); p1.setname("李四"); p1.gethobbies().add("游泳"); system.out.println(p); system.out.println(p1); } } |
我们拷贝了一个对象,并添加了一个兴趣爱好进去,看下打印结果
person{name=’张三’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑]}
person{name=’张三’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑]}
person{name=’张三’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑, 游泳]}
person{name=’李四’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑, 游泳]}
你会发现原来的对象的hobby也发生了变换。
其实导致这个问题的本质原因是我们只进行了浅拷贝,也就是只拷贝了引用,最终两个对象指向的引用是同一个,一个发生变化另一个也会发生变换,显然解决方法就是使用深拷贝。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @override public object clone(){ person person=null; try { person=(person)super.clone(); person.name=this.name; person.weight=this.weight; person.height=this.height; person.age=this.age; person.hobbies=(arraylist } catch (clonenotsupportedexception e) { e.printstacktrace(); } return person; } |
注意person.hobbies=(arraylist)this.hobbies.clone();,不再是直接引用而是进行了一份拷贝。再运行一下,就会发现原来的对象不会再发生变化了。
person{name=’张三’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑]}
person{name=’张三’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑]}
person{name=’张三’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑]}
person{name=’李四’, age=18, height=178.0, weight=65.0, hobbies=[篮球, 编程, 长跑, 游泳]}
其实有时候我们会更多的看到原型模式的另一种写法。
- 在clone函数里调用构造函数,构造函数的入参是该类对象。
1 2 3 4 | @override public object clone(){ return new person(this); } |
- 在构造函数中完成拷贝逻辑
1 2 3 4 5 6 7 | public person(person person){ this.name=person.name; this.weight=person.weight; this.height=person.height; this.age=person.age; this.hobbies= new arraylist } |
其实都差不多,只是写法不一样。
现在来挖挖android中的原型模式。
先看bundle类,该类实现了cloneable接口
1 2 3 4 5 6 7 8 9 | public object clone() { return new bundle(this); } public bundle(bundle b) { super(b); mhasfds = b.mhasfds; mfdsknown = b.mfdsknown; } |
然后是intent类,该类也实现了cloneable接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | @override public object clone() { return new intent(this); } public intent(intent o) { this.maction = o.maction; this.mdata = o.mdata; this.mtype = o.mtype; this.mpackage = o.mpackage; this.mcomponent = o.mcomponent; this.mflags = o.mflags; this.mcontentuserhint = o.mcontentuserhint; if (o.mcategories != null) { this.mcategories = new arrayset } if (o.mextras != null) { this.mextras = new bundle(o.mextras); } if (o.msourcebounds != null) { this.msourcebounds = new rect(o.msourcebounds); } if (o.mselector != null) { this.mselector = new intent(o.mselector); } if (o.mclipdata != null) { this.mclipdata = new clipdata(o.mclipdata); } } |
用法也显得十分简单,一旦我们要用的intent与现有的一个intent很多东西都是一样的,那我们就可以直接拷贝现有的intent,再修改不同的地方,便可以直接使用。
1 2 3 4 5 6 | uri uri = uri.parse("smsto:10086"); intent shareintent = new intent(intent.action_sendto, uri); shareintent.putextra("sms_body", "hello"); intent intent = (intent)shareintent.clone() ; startactivity(intent); |
网络请求中一个最常见的开源库okhttp中,也应用了原型模式。它就在okhttpclient这个类中,它实现了cloneable接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** returns a shallow copy of this okhttpclient. */ |
正如开头的注释returns a shallow copy of this okhttpclient,该clone方法返回了一个当前对象的浅拷贝对象。
至于其他框架中的原型模式,请读者自行发现。
策略模式
看下策略模式的定义
策略模式定义了一些列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变换。
乍一看,也没看出个所以然来。举个栗子吧。
假设我们要出去旅游,而去旅游出行的方式有很多,有步行,有坐火车,有坐飞机等等。而如果不使用任何模式,我们的代码可能就是这样子的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class travelstrategy { enum strategy{ walk,plane,subway } private strategy strategy; public travelstrategy(strategy strategy){ this.strategy=strategy; } public void travel(){ if(strategy==strategy.walk){ print("walk"); }else if(strategy==strategy.plane){ print("plane"); }else if(strategy==strategy.subway){ print("subway"); } } public void print(string str){ system.out.println("出行旅游的方式为:" str); } public static void main(string[] args) { travelstrategy walk=new travelstrategy(strategy.walk); walk.travel(); travelstrategy plane=new travelstrategy(strategy.plane); plane.travel(); travelstrategy subway=new travelstrategy(strategy.subway); subway.travel(); } } |
这样做有一个致命的缺点,一旦出行的方式要增加,我们就不得不增加新的else if语句,而这违反了面向对象的原则之一,对修改封闭。而这时候,策略模式则可以完美的解决这一切。
首先,需要定义一个策略接口。
1 2 3 4 | public interface strategy { void travel(); } |
然后根据不同的出行方式实行对应的接口
1 2 3 4 5 6 7 8 | public class walkstrategy implements strategy{ |
1 2 3 4 5 6 7 8 | public class planestrategy implements strategy{ |
1 2 3 4 5 6 7 8 | public class subwaystrategy implements strategy{ |
此外还需要一个包装策略的类,并调用策略接口中的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class travelcontext { strategy strategy; public strategy getstrategy() { return strategy; } public void setstrategy(strategy strategy) { this.strategy = strategy; } public void travel() { if (strategy != null) { strategy.travel(); } } } |
测试一下代码
1 2 3 4 5 6 7 8 9 10 11 | public class main { public static void main(string[] args) { travelcontext travelcontext=new travelcontext(); travelcontext.setstrategy(new planestrategy()); travelcontext.travel(); travelcontext.setstrategy(new walkstrategy()); travelcontext.travel(); travelcontext.setstrategy(new subwaystrategy()); travelcontext.travel(); } } |
输出结果如下
plane
walk
subway
可以看到,应用了策略模式后,如果我们想增加新的出行方式,完全不必要修改现有的类,我们只需要实现策略接口即可,这就是面向对象中的对扩展开放准则。假设现在我们增加了一种自行车出行的方式。只需新增一个类即可。
1 2 3 4 5 6 7 8 | public class bikestrategy implements strategy{ |
之后设置策略即可
1 2 3 4 5 6 7 | public class main { public static void main(string[] args) { travelcontext travelcontext=new travelcontext(); travelcontext.setstrategy(new bikestrategy()); travelcontext.travel(); } } |
而在android的系统源码中,策略模式也是应用的相当广泛的.最典型的就是属性动画中的应用.
我们知道,在属性动画中,有一个东西叫做插值器,它的作用就是根据时间流逝的百分比来来计算出当前属性值改变的百分比.
我们使用属性动画的时候,可以通过set方法对插值器进行设置.可以看到内部维持了一个时间插值器的引用,并设置了getter和setter方法,默认情况下是先加速后减速的插值器,set方法如果传入的是null,则是线性插值器。而时间插值器timeinterpolator是个接口,有一个接口继承了该接口,就是interpolator这个接口,其作用是为了保持兼容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private static final timeinterpolator sdefaultinterpolator = new acceleratedecelerateinterpolator(); private timeinterpolator minterpolator = sdefaultinterpolator; @override public void setinterpolator(timeinterpolator value) { if (value != null) { minterpolator = value; } else { minterpolator = new linearinterpolator(); } } @override public timeinterpolator getinterpolator() { return minterpolator; } |
1 2 3 4 5 6 | public interface interpolator extends timeinterpolator { // a new interface, timeinterpolator, was introduced for the new android.animation // package. this older interpolator interface extends timeinterpolator so that users of // the new animator-based animations can use either the old interpolator implementations or // new classes that implement timeinterpolator directly. } |
此外还有一个baseinterpolator插值器实现了interpolator接口,并且是一个抽象类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | abstract public class baseinterpolator implements interpolator { private int mchangingconfiguration; /** * @hide */ public int getchangingconfiguration() { return mchangingconfiguration; } /** * @hide */ void setchangingconfiguration(int changingconfiguration) { mchangingconfiguration = changingconfiguration; } } |
平时我们使用的时候,通过设置不同的插值器,实现不同的动画速率变换效果,比如线性变换,回弹,自由落体等等。这些都是插值器接口的具体实现,也就是具体的插值器策略。我们略微来看几个策略。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class linearinterpolator extends baseinterpolator implements nativeinterpolatorfactory { public linearinterpolator() { } public linearinterpolator(context context, attributeset attrs) { } public float getinterpolation(float input) { return input; } /** @hide */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class acceleratedecelerateinterpolator extends baseinterpolator implements nativeinterpolatorfactory { public acceleratedecelerateinterpolator() { } |
内部使用的时候直接调用getinterpolation方法就可以返回对应的值了,也就是属性值改变的百分比。
属性动画中另外一个应用策略模式的地方就是估值器,它的作用是根据当前属性改变的百分比来计算改变后的属性值。该属性和插值器是类似的,有几个默认的实现。其中typeevaluator是一个接口。
1 2 3 4 5 | public interface typeevaluator<t> { public t evaluate(float fraction, t startvalue, t endvalue); } |
1 2 3 4 5 6 7 | public class intevaluator implements typeevaluator<integer> { public integer evaluate(float fraction, integer startvalue, integer endvalue) { int startint = startvalue; return (int)(startint fraction * (endvalue - startint)); } } |
1 2 3 4 5 6 7 | public class floatevaluator implements typeevaluator<number> { public float evaluate(float fraction, number startvalue, number endvalue) { float startfloat = startvalue.floatvalue(); return startfloat fraction * (endvalue.floatvalue() - startfloat); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class pointfevaluator implements typeevaluator<pointf> { private pointf mpoint; public pointfevaluator() { } public pointfevaluator(pointf reuse) { mpoint = reuse; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class argbevaluator implements typeevaluator { private static final argbevaluator sinstance = new argbevaluator(); public static argbevaluator getinstance() { return sinstance; } public object evaluate(float fraction, object startvalue, object endvalue) { int startint = (integer) startvalue; int starta = (startint >> 24) & 0xff; int startr = (startint >> 16) & 0xff; int startg = (startint >> 8) & 0xff; int startb = startint & 0xff; int endint = (integer) endvalue; int enda = (endint >> 24) & 0xff; int endr = (endint >> 16) & 0xff; int endg = (endint >> 8) & 0xff; int endb = endint & 0xff; return (int)((starta (int)(fraction * (enda - starta))) << 24) | (int)((startr (int)(fraction * (endr - startr))) << 16) | (int)((startg (int)(fraction * (endg - startg))) << 8) | (int)((startb (int)(fraction * (endb - startb)))); } } |
上面的都是一些系统实现好的估值策略,在内部调用估值器的evaluate方法即可返回改变后的值了。我们也可以自定义估值策略。这里就不展开了。
当然,在开源框架中,策略模式也是无处不在的。
首先在volley中,策略模式就能看到。
有一个重试策略接口
1 2 3 4 5 6 7 8 9 10 11 | public interface retrypolicy { public int getcurrenttimeout();//获取当前请求用时(用于 log) public int getcurrentretrycount();//获取已经重试的次数(用于 log) public void retry(volleyerror error) throws volleyerror;//确定是否重试,参数为这次异常的具体信息。在请求异常时此接口会被调用,可在此函数实现中抛出传入的异常表示停止重试。 } |
在volley中,该接口有一个默认的实现defaultretrypolicy,volley 默认的重试策略实现类。主要通过在 retry(…) 函数中判断重试次数是否达到上限确定是否继续重试。
1 2 3 | public class defaultretrypolicy implements retrypolicy { ... } |
而策略的设置是在request类中
1 2 3 4 5 6 7 8 9 10 11 | public abstract class request<t> implements comparable<request<t>> { private retrypolicy mretrypolicy; public request setretrypolicy(retrypolicy retrypolicy) { mretrypolicy = retrypolicy; return this; } public retrypolicy getretrypolicy() { return mretrypolicy; } } |
此外,各大网络请求框架,或多或少都会使用到缓存,缓存一般会定义一个cache接口,然后实现不同的缓存策略,如内存缓存,磁盘缓存等等,这个缓存的实现,其实也可以使用策略模式。直接看volley,里面也有缓存。
定义了一个缓存接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | /** * an interface for a cache keyed by a string with a byte array as data. */ public interface cache { /** * retrieves an entry from the cache. * @param key cache key * @return an {@link entry} or null in the event of a cache miss */ public entry get(string key); /** * adds or replaces an entry to the cache. * @param key cache key * @param entry data to store and metadata for cache coherency, ttl, etc. */ public void put(string key, entry entry); /** * performs any potentially long-running actions needed to initialize the cache; * will be called from a worker thread. */ public void initialize(); /** * invalidates an entry in the cache. * @param key cache key * @param fullexpire true to fully expire the entry, false to soft expire */ public void invalidate(string key, boolean fullexpire); /** * removes an entry from the cache. * @param key cache key */ public void remove(string key); /** * empties the cache. */ public void clear(); /** * data and metadata for an entry returned by the cache. */ public static class entry { /** the data returned from cache. */ public byte[] data; /** etag for cache coherency. */ public string etag; /** date of this response as reported by the server. */ public long serverdate; /** the last modified date for the requested object. */ public long lastmodified; /** ttl for this record. */ public long ttl; /** soft ttl for this record. */ public long softttl; /** immutable response headers as received from server; must be non-null. */ public map /** true if the entry is expired. */ public boolean isexpired() { return this.ttl < system.currenttimemillis(); } /** true if a refresh is needed from the original data source. */ public boolean refreshneeded() { return this.softttl < system.currenttimemillis(); } } } |
它有两个实现类nocache和diskbasedcache,使用的时候设置对应的缓存策略即可。
在android开发中,viewpager是一个使用非常常见的控件,它的使用往往需要伴随一个indicator指示器。如果让你重新实现一个viewpager,并且带有indicator,这时候,你会不会想到用策略模式呢?在你自己写的viewpager中(不是系统的,当然你也可以继承系统的)持有一个策略接口indicator的变量,通过set方法设置策略,然后viewpager滑动的时候调用策略接口的对应方法改变指示器。默认提供几个indicator接口的实现类,比如圆形指示器circleindicator、线性指示器lineindicator、tab指示器tabindicator、图标指示器iconindicator 等等等等。有兴趣的话自己去实现一个吧。
总结
以上是尊龙游戏旗舰厅官网为你收集整理的android开发中常见的设计模式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: