Android设计模式——单例模式(Singleton)
生活随笔
收集整理的這篇文章主要介紹了
Android设计模式——单例模式(Singleton)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
二十三種設(shè)計(jì)模式分為三大類:
創(chuàng)建型模式,共五種:工廠方法模式、抽象工廠模式、單例模式、建造者模式、原型模式。
結(jié)構(gòu)型模式,共七種:適配器模式、裝飾器模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。
行為型模式,共十一種:策略模式、模板方法模式、觀察者模式、迭代子模式、責(zé)任鏈模式、命令模式、備忘錄模式、狀態(tài)模式、訪問者模式、中介者模式、解釋器模式。?
1 package com.example.main; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.os.Bundle; 6 import android.widget.LinearLayout; 7 import android.widget.TextView; 8 9 /* 10 * Android設(shè)計(jì)模式——單例模式(Singleton) 11 */ 12 13 public class Singleton extends Activity { 14 15 private LinearLayout ly; 16 private LinearLayout sly; 17 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.create); 22 23 ly = (LinearLayout) findViewById(R.id.creately); 24 sly = (LinearLayout) findViewById(R.id.singly); 25 26 Android google = new Android("谷歌",ly,this); 27 google.setName(); 28 29 Android huawei = new Android("華為",ly,this); 30 huawei.setName(); 31 32 //第一次實(shí)例化 33 IOS ios = IOS.getInstance("蘋果", sly, this); 34 ios.setName(); 35 36 //第二次調(diào)用 37 IOS samsung = IOS.getInstance("三星", ly, this); 38 samsung.setName(); 39 } 40 41 /* 42 * Android廠商 43 */ 44 45 class Android{ 46 47 private String name; 48 private LinearLayout ly; 49 private TextView tv; 50 private Context context; 51 52 public Android(String name,LinearLayout ly,Context context){ 53 this.name = name; 54 this.ly = ly; 55 this.context = context; 56 } 57 58 public void setName() { 59 tv = new TextView(context); 60 this.tv.setText(name + "的Android設(shè)備"); 61 this.ly.addView(this.tv); 62 } 63 } 64 65 /* 66 * 蘋果廠商 67 */ 68 69 static class IOS{ 70 71 private String name; 72 private LinearLayout ly; 73 private TextView tv; 74 private Context context; 75 76 //禁止引用 77 78 private static IOS instance = null; 79 80 //私有構(gòu)造函數(shù),防止被實(shí)例化。 81 82 private IOS(){} 83 84 private IOS(String name,LinearLayout ly,Context context){ 85 this.name = name; 86 this.ly = ly; 87 this.context = context; 88 } 89 90 //創(chuàng)建實(shí)例 91 92 public static IOS getInstance(String name,LinearLayout ly,Context context){ 93 94 if (instance == null) { 95 instance = new IOS(name,ly, context); 96 } 97 return instance; 98 } 99 100 public void setName() { 101 tv = new TextView(context); 102 tv.setText("IOS只屬于"+name+"公司"); 103 ly.addView(tv); 104 } 105 } 106 } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/yuge790615/p/4783621.html
總結(jié)
以上是生活随笔為你收集整理的Android设计模式——单例模式(Singleton)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CPlus的简单线程的制作
- 下一篇: easyUI Combobox自定义调整