android常用的设计模式总结 一

来源:互联网 发布:易建联里约奥运会数据 编辑:程序博客网 时间:2024/04/30 09:22

前言

对于开发人员来说,设计模式是提高编程水平的一个非常重要的门槛.
以前写过一些设计模式的文章,有兴趣可以参考一下.
这一次来写一下android中设计模式的应用,相信你会对设计模式有一个更深入的理解.
什么是设计模式?
设计模式大总结-创建型模式
设计模式大总结2-结构型模式

单例模式

public class Singleton {    private static Singleton instance;    public static Singleton getInstace(){        if (instance==null){            synchronized (Singleton.class){                if (instance==null) {                    instance = new Singleton();                }            }        }        return instance;    }}
  • 使用synchronized 进行同步处理,并且双重判断是否为null,是因为如果有多个线程同时访问,这时候前一个线程创建了一个实例出来完毕后,另一个线程获得锁进入该同步代码,实例已经存在,没必要再次创建,因此这个判断是否是null还是必须的。
  • 我一般用在工具类的创建上
  • `

工厂模式

public class FragmentFactory {    private static HashMap<Integer, BaseFragment> hashMap = new HashMap<Integer, BaseFragment>();    private static int currentPosition;    public static BaseFragment createFragment(int position) {        //根据传递进来的索引去生成Fragment(内存缓存获取,直接new)        BaseFragment fragment = hashMap.get(position);        currentPosition = position;        if (fragment != null) {            return fragment;        } else {            switch (position) {                case 4:                    fragment = new SelectProductFragment();                    break;                case 0:                    fragment = new StartFragment();                    break;                case 1:                    //创建首页对应的Fragment对象                    //每一个Fragment都是在onCreatView方法中返回界面view效果                    fragment = new AppointFragment();                    break;                case 2:                    fragment = new PackageFragment();                    break;                case 5:                    fragment = new ReportFormFragment();                    break;                case 6:                    fragment = new CaddieManageFragment();                    break;                case 3:                    fragment = new CarInfWebViewFragment();                    break;                case 7:                    fragment = new Start2Fragment();                    break;            }            //生成了fragment对象后,需要将其加入内存中hashMap            hashMap.put(position, fragment);            return fragment;        }    }}
  • 工厂模式可以用在用在页面缓存.

Build模式

package com.example.king.designpatternsdemoforandroid;/** * Created by king on 2017/3/9. */public class Person {    private String name;    private int age;    private double height;    private double weight;    private Person(Builder builder) {        this.name=builder.name;        this.age=builder.age;    }    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;    }    static class Builder{        private String name;        private int age;        public Person build(){            return new Person(this);        }        public Builder name(String name){            this.name=name;            return this;        }        public Builder age(int age){            this.age=age;            return this;        }    }}

调用方式

  Person.Builder person = new Person.Builder();                person.age(1).name("11");

Builder模式是不是也很面熟?是的,我们的AlertDialog就是这样子写的

 AlertDialog.Builder builder=new AlertDialog.Builder(this);        AlertDialog dialog=builder.setTitle("标题")                .setIcon(android.R.drawable.xx)                .setView(R.layout.xx)                .setPositiveButton("确定", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                    }                })                .setNegativeButton("取消", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                    }                })                .create();        dialog.show();

还有StringBuilder

  StringBuilder builder = new StringBuilder();        builder.append("aa").append("bb");

原型模式

研究过浅拷贝和深拷贝的人对这样的例子一定不陌生

package com.example.king.designpatternsdemoforandroid;/** * Created by king on 2017/3/9. */public class Person2 implements Cloneable{    private String name;    private int age;    private double height;    private double weight;    public Person2(){    }    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 +                '}';    }    @Override    public Object clone(){        Person2 person=null;        try {            person=(Person2)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;    }}

调用

        Person2 p=new Person2();        p.setAge(18);        p.setName("张三");        p.setHeight(178);        p.setWeight(65);        System.out.println(p);        Person2 p1= (Person2) p.clone();        System.out.println(p1);        p1.setName("李四");        System.out.println(p);        System.out.println(p1);

结果

System.out: Person{name='张三', age=18, height=178.0, weight=65.0}System.out: Person{name='张三', age=18, height=178.0, weight=65.0}System.out: Person{name='张三', age=18, height=178.0, weight=65.0}System.out: Person{name='李四', age=18, height=178.0, weight=65.0}

其实这就是一个原型模式

我们经常用的Intent就是一个原型模式的使用者

@Override  public Object clone() {      return new Intent(this);  }  /**  * Copy constructor.  */  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;      if (o.mCategories != null) {          this.mCategories = new ArraySet<String>(o.mCategories);      }      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);      }  }  
1 0
原创粉丝点击