Android Ap 开发 设计模式第五篇:单件模式

Singleton Pattern

名称由来

java 是一门面向对象的语言,android 用的也是java 开发ap ,在java/C# 里面所有的物体(类)都可以看作是一个对象,而要使用这个对象无外乎为它在内存里面分配一个对象,一般情况下最直接的方法是new 一个对象,让它存在于内存中。
单件/例模式是所有设计模式中可以说是最简单最易懂的一种编程方式 ,想保证某个特定类的对象实例绝对只有一个时,想在程序上表达出对象实例只会有一个时,这种做法就被称为单件/例模式。
Singleton 是指只有1个元素的集合。就是因为它只会有1 个对象实例,因而得名。
由于其简单性,在此就不把UML图画出来了。本篇共涉及两个类,一个为测试单件/例模式的类,一个为普通类,用来区分单例模式与普通对象的区别。

单件/例 类 Singleton


public class Singleton { private static Singleton singleton=new Singleton(); private Singleton(){ System.out.println("对象己产生"); } public static Singleton getInstance(){ return singleton; } }
该类把singleton 定义为静态字段,再以Singleton 类的对象实例进行初始化,这个初始化的操作仅在加载Singleton 类时进行一次。
类的构造函数为私有的,主要是为了禁止从非Singleton 类调用构造函数。所以直接使用new Singleton() 会发生编译的错误 。
单件/例 模式存在的必要只是为了确保对象只产生一个实例,如果编码小心该模式一般没什么存在的必要,但谁能保证呢?存在即合理。

normal 类是一个空类


public class normal { }

android 界面入口测试该 单件/例模式 SingletonPatternActivity 类


public class SingletonPatternActivity extends Activity { /** Called when the activity is first created. */ @Override public void _disibledevent=>new _disibledevent=>public void _disibledevent=>// TODO Auto-generated method stub Singleton obj1=Singleton.getInstance(); Singleton obj2=Singleton.getInstance(); normal obj3=new normal(); normal obj4 =new normal(); if(obj1==obj2){ ((EditText) findViewById(R.id.EditText01)).setText("obj1和obj2是同一对象实例"); } else { ((EditText) findViewById(R.id.EditText01)).setText("obj1和obj2不是同一对象实例"); } if(obj3==obj4){ ((EditText) findViewById(R.id.EditText02)).setText("obj3和obj4是同一对象实例"); }else { ((EditText) findViewById(R.id.EditText02)).setText("obj3和obj4不是同一对象实例"); } } }); } }

测试结果

Android Ap 开发 设计模式第五篇:单件模式
该模式经常在编写 android 应用时,如果应用有使用Application用得比较多,详细的代码可以参考jamendo 开源播放器,里面就有在Application里面使用单件/例 模式。
源码下载:
单件/例 模式

再发个求职信息:
求职android(可胜任Framework及 以上工作。一年半经验) 、Windows Phone 7(软件、XNA) 开发工作。
Tags: 

延伸阅读

最新评论

发表评论