单列设计模式,构造方法私有化
来源:互联网 发布:淘宝主播逢丁吉吉 编辑:程序博客网 时间: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
- 单列设计模式,构造方法私有化
- 构造方法私有化 (单态设计模式)
- 构造方法私有化---单例设计模式
- 构造方法私有化--単例设计模式
- 构造方法私有化及单态设计模式
- Java 单例设计模式——构造方法私有化
- 0008_构造方法私有化与单例设计模式
- 构造方法私有化和单例模式
- 构造方法私有化及单态模式
- 构造方法私有化及单态模式
- [Java]构造方法私有化-->单例模式
- 构造方法私有化demo---单例模式
- Java构造方法私有化-->单例模式-->Runtime类的设计
- java面向对象(十三) 构造方法私有化(单例与多例设计模式)
- 构造方法私有化作用
- java构造方法私有化
- 构造方法私有化作用
- 构造方法私有化
- Linux网络编程之套接字基础
- asdfghjk
- 梅
- HTTP Status 404 Tomcat Apache & tomcat server location property is greyed in Eclipse
- AngularJS项目中使用中的几点注意事项
- 单列设计模式,构造方法私有化
- tableview样式
- 关系型数据库管理系统简介
- 欢迎使用CSDN-markdown编辑器
- [Leetcode]Trapping Rain Water
- Android生成圆形图片
- HDU-2191-悼念512汶川大地震遇难同胞——珍惜现在,感恩生活(多重背包)
- SVN使用
- css_selector的相关匹配问题