单列设计模式,构造方法私有化

来源:互联网 发布:淘宝主播逢丁吉吉 编辑:程序博客网 时间:2024/06/10 19:16

什么是构造方法:

class Person   //人类
{
       public Person(String n,int a)   //构造方法 
       {
                name = n;
                age = a;
       }
       private string name;
      private int age;
}

static void main(String[] args)
{
          Person  p  = new Person("张三",14);//这就是作用
}

 

构造方法私有化:

范例1:
class Single{

 private Single() ;  //将构造方法私有化

 public void print(){
  System.put.println("Hello world!!");
 }
}
public class SingleDemo01{
 public static void main(String args[]){
  Single s =  null ;  //声明对象
  s = new Single ;  //实例化对象
  s.print();
 }
}
 
运行结果:
不能编译,因为Single()是私有化的构造方法,在“s = new Single()”中则不可以执行。
 
单列设计模式:
 
public class CoolWeatherDB {    //数据库名//    public static final String DB_NAME = "cool_weather";    //数据库版本//    public static final int VERSION = 1;    public static CoolWeatherDB coolWeatherDB;    private SQLiteDatabase db;    //将构造方法私有化//    private CoolWeatherDB(Context context) {        CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,DB_NAME,null,VERSION);        db = dbHelper.getWritableDatabase();    }    //获取CoolWeather实例//    public synchronized static CoolWeatherDB getInstance(Context context){        if (coolWeatherDB == null){            coolWeatherDB = new CoolWeatherDB(context);        }        return coolWeatherDB;    }
 
总结:
在类中如果声明了私有化的构造方法,那么主方法中若取得并且实例化对象可以用以下方法:
·在类中进行对私有化的构造方法的实例化。
·用static的get方法对实例化的对象进行取值。
·在主方法中取得实例化对象用get方法。
 
 
此程序的意义:
如果现在一个类只能有一个实例化对象的话,那么这样的设计就称为--单例设计。(比如数据库)
当整个系统中只需要一个实例化的对象时,就是用此设计模式。

 

 

0 0
原创粉丝点击