单例设计模式以及衍生的多例设计模式

来源:互联网 发布:vmware mac os 10.12 编辑:程序博客网 时间:2024/06/17 20:28
package com.tongbu;
/**
 * 单例设计模式分为两类:
 * ①是俄汉式
 * ②是懒汉式
 * 以下程序是俄汉式:不管程序中有没有使用,都实例化对象。
 * @author Administrator
 *
 */
public class DemoSingleton {
public static void main(String[] args) {
Singleton in = null;
in = Singleton.getInstance();
in.print();
}
}
class Singleton {
private static final Singleton INSTANCE = new Singleton();//就是这里
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {// 构造方法私有花了


}
public void print() {
System.out.println("单例设计模式!");
}

}



package com.tongbu;
/**
 * 单例设计模式分为两类: ①是俄汉式 ②是懒汉式 以下程序是懒汉式:在程序第一次使用是才实例化对象。
 * 
 * @author Administrator
 *
 */
public class DemoSingleton2 {
public static void main(String[] args) {
Singleton2 in = null;
in = Singleton2.getInstance();
in.print();
}
}
class Singleton2 {
private static Singleton2 instance;
public static Singleton2 getInstance() {
if (instance == null) {//就是这里,第一次使用时初始化
instance = new Singleton2();
}
return instance;
}
private Singleton2() {// 构造方法私有化了
}


public void print() {
System.out.println("单例设计模式!懒汉式");
}
}


多例设计模式:

package com.tongbu;
/**
 * 多例设计模式只是单例设计模式的一个衍生品,本质上还是:
 * 构造方法私有化,内部产生实例化对象,之不过单例设计模式只有一个,多例设计模式产生多个;
 *   一定要理解他们的共同出发点:限制对象的使用。
 * @author zhang
 */
public class DemoDuoLI {
public static void main(String[] args) {
Sex sex = Sex.getInstance(Sex.MALE_CH);
System.out.println(sex);
}
}
class Sex {
public static final int MALE_CH = 1;
public static final int FEMALE_CH = 2;
private String sex;
private Sex(String sex) {
super();
this.sex = sex;
}
private static final Sex MALE = new Sex("男");
private static final Sex FEMALE = new Sex("女");
public static Sex getInstance(int ch) {
switch (ch) {
case MALE_CH:
return MALE;
case FEMALE_CH:
return FEMALE;
default:
return null;
}
}
@Override
public String toString() {
return sex;
}
}









1 0
原创粉丝点击