您的位置:首页 > 移动开发 > Android开发

Android开发常用的设计模式

2018-03-30 17:56 260 查看
Android常用的设计模式有如下几种:

单例模式、Build模式、观察者模式、原型模式、策略模式

设计模式的六大原则:https://mp.csdn.net/postedit/79623206

1、单例模式

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这样做有以下几个优点对于那些比较耗内存的类,只实例化一次可以大大提高性能,尤其是在移动开发中。保持程序运行的时候该中始终只有一个实例存在内存中
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还是必须的。

2、Build模式

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示假设有一个Person类,我们通过该Person类来构建一大批人,这个Person类里有很多属性,最常见的比如name,age,weight,height等等,并且我们允许这些值不被设置,也就是允许为null,该类的定义如下。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;}}然后我们为了方便可能会定义一个构造方法。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类的构造函数,代码如下。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.Builder builder=new Person.Builder();Person person=builder.name("张三").age(18).height(178.5).weight(67.4).build();Builder模式在各个框架中的应用,例如Gson、EventBus、OkHttp等

3、观察者模式

义对象间的一种一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都能得到通知并被自动更新有一种短信服务,比如天气预报服务,一旦你订阅该服务,你只需按月付费,付完费后,每天一旦有天气信息更新,它就会及时向你发送最新的天气信息杂志的订阅,你只需向邮局订阅杂志,缴纳一定的费用,当有新的杂志时,邮局会自动将杂志送至你预留的地址。     观察上面两个情景,有一个共同点,就是我们无需每时每刻关注我们感兴趣的东西,我们只需做的就是订阅感兴趣的事物,比如天气预报服务,杂志等,一旦我们订阅的事物发生变化,比如有新的天气预报信息,新的杂志等,被订阅的事物就会即时通知到订阅者,即我们。而这些被订阅的事物可以拥有多个订阅者,也就是一对多的关系。当然,严格意义上讲,这个一对多可以包含一对一,因为一对一是一对多的特例,没有特殊说明,本文的一对多包含了一对一。然后我们看一下观察者模式的几个重要组成。观察者,我们称它为Observer,有时候我们也称它为订阅者,即Subscriber被观察者,我们称它为Observable,即可以被观察的东西,有时候还会称之为主题,即Subject至于观察者模式的具体实现,这里带带大家实现一下场景一,其实java中提供了Observable类和Observer接口供我们快速的实现该模式,但是为了加深印象,我们不使用这两个类。场景1中我们感兴趣的事情是天气预报,于是,我们应该定义一个Weather实体类。
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;
}

@Override
public String toString() {
return "Weather{" +
"description='" + description + '\'' +
'}';
}
}
然后定义我们的被观察者,我们想要这个被观察者能够通用,将其定义成泛型。内部应该暴露register和unregister方法供观察者订阅和取消订阅,至于观察者的保存,直接用ArrayList即可,此外,当有主题内容发送改变时,会即时通知观察者做出反应,因此应该暴露一个notifyObservers方法,以上方法的具体实现见如下代码。public class Observable<T> {List<Observer<T>> mObservers = new ArrayList<Observer<T>>();public void register(Observer<T> observer) {if (observer == null) {throw new NullPointerException("observer == null");}synchronized (this) {if (!mObservers.contains(observer))mObservers.add(observer);}}public synchronized void unregister(Observer<T> observer) {mObservers.remove(observer);}public void notifyObservers(T data) {for (Observer<T> observer : mObservers) {observer.onUpdate(this, data);}}}而我们的观察者,只需要实现一个观察者的接口Observer,该接口也是泛型的。其定义如下。public interface Observer<T> {void onUpdate(Observable<T> observable,T data);}一旦订阅的主题发送变换就会回调该接口。我们来使用一下,我们定义了一个天气变换的主题,也就是被观察者,还有两个观察者观察天气变换,一旦变换了,就打印出天气信息,注意一定要调用被观察者的register进行注册,否则会收不到变换信息。而一旦不敢兴趣了,直接调用unregister方法进行取消注册即可
public class Main {
public static void main(String [] args){
Observable<Weather> observable=new Observable<Weather>();
Observer<Weather> observer1=new Observer<Weather>() {
@Override
public void onUpdate(Observable<Weather> observable, Weather data) {
System.out.println("观察者1:"+data.toString());
}
};
Observer<Weather> observer2=new Observer<Weather>() {
@Override
public void onUpdate(Observable<Weather> observable, Weather data) {
System.out.println("观察者2:"+data.toString());
}
};

observable.register(observer1);
observable.register(observer2);

Weather weather=new Weather("晴转多云");
observable.notifyObservers(weather);

Weather weather1=new Weather("多云转阴");
observable.notifyObservers(weather1);

observable.unregister(observer1);

Weather weather2=new Weather("台风");
observable.notifyObservers(weather2);

}
}
观察者1:Weather{description=’晴转多云’}
观察者2:Weather{description=’晴转多云’}
观察者1:Weather{description=’多云转阴’}
观察者2:Weather{description=’多云转阴’}
观察者2:Weather{description=’台风’}

4、策略模式

策略模式定义了一些列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变换。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语句,而这违反了面向对象的原则之一,对修改封闭。而这时候,策略模式则可以完美的解决这一切。首先,需要定义一个策略接口。public interface Strategy {void travel();}然后根据不同的出行方式实行对应的接口public class WalkStrategy implements Strategy{@Overridepublic void travel() {System.out.println("walk");}}
public class PlaneStrategy implements Strategy{

@Override
public void travel() {
System.out.println("plane");
}

}
此外还需要一个包装策略的类,并调用策略接口中的方法
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();
}
}
}
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();
}
}

5、原型模式

用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。首先我们定义一个Person类
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;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
", weight=" + weight +
'}';
}
}
实现Cloneable接口
public class Person implements Cloneable{
Override
public Object clone(){
return null;
}
}
@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;
}
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集合,就像这样子
private ArrayList<String> hobbies=new ArrayList<String>();

public ArrayList<String> getHobbies() {
return hobbies;
}

public void setHobbies(ArrayList<String> hobbies) {
this.hobbies = hobbies;
}
在进行拷贝的时候要格外注意,如果你直接按之前的代码那样拷贝
@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;
}
使用测试代码进行测试
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 <String> hobbies=new ArrayList<String>();
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也发生了变换。其实导致这个问题的本质原因是我们只进行了浅拷贝,也就是只拷贝了引用,最终两个对象指向的引用是同一个,一个发生变化另一个也会发生变换,显然解决方法就是使用深拷贝。@Overridepublic 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<String>)this.hobbies.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return person;}注意person.hobbies=(ArrayList)this.hobbies.clone();,不再是直接引用而是进行了一份拷贝。再运行一下,就会发现原来的对象不会再发生变化了。
在clone函数里调用构造函数,构造函数的入参是该类对象。
@Overridepublic Object clone(){return new Person(this);}
public Person(Person person){this.name=person.name;this.weight=person.weight;this.height=person.height;this.age=person.age;this.hobbies= new ArrayList<String>(hobbies);}
Intent类,该类也实现了Cloneable接口,用法也显得十分简单,一旦我们要用的Intent与现有的一个Intent很多东西都是一样的,那我们就可以直接拷贝现有的Intent,再修改不同的地方,便可以直接使用。
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接口

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: