Java/Android 设计模式<一> 单例模式+建造者模式

567 阅读2分钟
原文链接: blog.csdn.net

Java/Android 设计模式

android中的设计模式很多,可以有效提高开发效率,代码效率以及project新能;

1

单例模式:java/android中最常用的设计模式:

private static volatile ApiClient mApiClient;

public static ApiClient getInstance(Context context) {
        if (mApiClient == null) {
            synchronized (ApiClient.class) {
                mApiClient = new ApiClient(context);
            }
        }
        return mApiClient;
    }

需要注意几点:
1.私有化构造,其他类不能new 对象;
2.static修饰单例,其他类可以类名. 来调用单例
3.volatile 修饰单例:在每次访问单例时候,必须必须从共享内存中读取;若成员变量值变化,则强制把变化值放入共享内存中,保证值得唯一性;
4.synchronized同步锁的修饰; 因为在项目中如果有很大的并发量的情况下,有可能造成同时又多个程序执行这个类实例化的方法,因此我们需要在创建类实例化方法的时候添加同步执行。并且双重判断是否为null,我们看到synchronized (Singleton.class)里面又进行了是否为null的判断,这是因为一个线程进入了该代码,如果另一个线程在等待,这时候前一个线程创建了一个实例出来完毕后,另一个线程获得锁进入该同步代码,实例已经存在,没必要再次创建,因此这个判断是否是null还是必须的。

2.

建造者模式

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);
        }
    }

由上代码可以看出诸如像person这样的bean类,其中参数很多,如果选择性的增减参数创建一堆构造显然是不行的,所以在person内部创建内部类Builder用来选择性的初始化参数—->在Builder提供将初始化后builder作为参数创建person对象

Person.Builder builder=new Person.Builder();
Person person=builder
        .name("张三")
        .age(18)
        .height(100)
        .weight(100)
        .build();

以上代码就已经很明了了,android开发中retrofit,dialog都有用到建造者模式; //eg:retrofit:

mRetrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)//设置baseurl参数
                .client(mOkHttpClient)//设置OkHttpClient实例
                .addConverterFactory(GsonConverterFactory.create())//gson转化工厂
                .build();