构造方法私有化
-
单例设计模式(例:Runtime类)(Singleton)
大部分时候都把类的构造方法定义为public访问访问权限,允许任何类自由创建该类的对象。但在某些时候,允许其他类自由创建该类的对象没有任何意义,还可能造成系统性能下降(因为频繁的创造对象,回收对象带来系统开销问题)
如果一个类只能创建一个实例,则把这个类称为单例(Singleton)类
要求:
- 为了避免其他类自由创建该类的实例,应该把该类的构造方法使用private修饰,从而把该类的所有构造方法隐藏起来。
- 一旦把该类的构造方法隐藏起来,就需要提供一个public方法作为该类的访问点,用于创建该类的对象,且该方法必须使用static修饰(因为i到用该方法之前还不存在对象,因此调用该方法的不可能是对象,只能是类)。
- 该类还必须缓存已经创建的对象,否则该类无法知道是否曾创建过对象,也就无法保证只创建一个对象。
- 该类需要使用一个成员变量来保存曾经创建过的对象,因为该成员变量需要被上面的静态方法访问,股改变量必须使用static修饰。
//饿汉式
class test{
private static final test TEST1 = new test();
public void print() {
System.out.println("helloworld");
}
private test() {}
public static test getTest1() {
return TEST1;
}
}
/*懒汉式
class test{
private static final test TEST1 = null;
public void print(){
System.out.println("helloworld");
}
private test() {}
public static test getTest1(){
if(TEST1 == null){
TEST1 = new test();
}
return TEST1;
}
}
*/
public class demo {
public static void main(String[] args) {
test test2 = test.getTest1();
test test3 = test.getTest1();
test2.print();
test3.print();
System.out.println("**********");
//检查是否只创建一个对象。
System.out.println(test2);
System.out.println(test3);
}
}
结果:
helloworld
helloworld
**********
Task.test@15db9742
Task.test@15db9742
很明显只产生了一个对象
-
多例设计模式
class Sex{
private String title;
private static final Sex MALE = new Sex("男");
private static final Sex FEMALE = new Sex("女");
private Sex(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String toString() {
return this.title;
}
public static Sex getInstance(String ch) {
switch(ch) {
case "man" :
return MALE;
case "woman" :
return FEMALE;
default :
return null;
}
}
}
public class TestDemo1 {
public static void main(String[] args) {
Sex sex1 = Sex.getInstance("man");
System.out.println(sex1);
Sex sex2 = Sex.getInstance("woman");
System.out.println(sex2);
}
}
结果:
男
女
以上代码可以产生2个实例对象。