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

Android设计模式——单例模式(Singleton)

2015-09-05 18:10 405 查看
二十三种设计模式分为三大类:

创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

package com.example.main;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

/*
* Android设计模式——单例模式(Singleton)
*/

public class Singleton extends Activity {

private LinearLayout ly;
private LinearLayout sly;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);

ly = (LinearLayout) findViewById(R.id.creately);
sly = (LinearLayout) findViewById(R.id.singly);

Android google = new Android("谷歌",ly,this);
google.setName();

Android huawei = new Android("华为",ly,this);
huawei.setName();

//第一次实例化
IOS ios = IOS.getInstance("苹果", sly, this);
ios.setName();

//第二次调用
IOS samsung = IOS.getInstance("三星", ly, this);
samsung.setName();
}

/*
* Android厂商
*/

class Android{

private String name;
private LinearLayout ly;
private TextView tv;
private Context context;

public Android(String name,LinearLayout ly,Context context){
this.name = name;
this.ly = ly;
this.context = context;
}

public void setName() {
tv = new TextView(context);
this.tv.setText(name + "的Android设备");
this.ly.addView(this.tv);
}
}

/*
* 苹果厂商
*/

static class IOS{

private String name;
private LinearLayout ly;
private TextView tv;
private Context context;

//禁止引用

private static IOS instance = null;

//私有构造函数,防止被实例化。

private IOS(){}

private IOS(String name,LinearLayout ly,Context context){
this.name = name;
this.ly = ly;
this.context = context;
}

//创建实例

public static IOS getInstance(String name,LinearLayout ly,Context context){

if (instance == null) {
instance = new IOS(name,ly, context);
}
return instance;
}

public void setName() {
tv = new TextView(context);
tv.setText("IOS只属于"+name+"公司");
ly.addView(tv);
}
}
}


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