设计模式之单例模式
设计模式之单例模式
1,定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点;
2,模式:
public class Singleton{
private static Singleton singleInstance;
private Singleton(){
}
public statoc Singleton GetInstance(){
if(singleInstance==null){
singleInstance = new Singleton();
}
return singleInstance;
}
}
3,适用情况:
1),当类只有一个实例而且第三方可以从一个公共的访问点访问它时;
2),当一个唯一的实例可以通过子类化来发展,而且第三方需要在不方便改造代码的情况下就能适用一个扩展的实例时;
4,优点:
1),对唯一的实例做出访问控制;
2),允许改变实例数目,事实上单例模式黑只是实例有限的类的一种特例,通过计数等方式可以做到双模式,三例模式等需要实例化有限次的 类;
5,代码:
主类:Main.class
public class Main {
public static void main(String[] args){
Husband husband = new Husband();
System.out.println("大龄男青年挑选了一个漂亮姑娘");
husband.ChooseWife();
System.out.println("大龄男青年觉得不错,决定跟漂亮姑娘去结婚");
husband.GetMarry();
Mother mother = new Mother();
System.out.println("大龄男青年的母亲想要见见媳妇");
mother.CheckDaughterView();
}
}
Husband类:Husband.class:
public class Husband {
private Wife myWife = null;
public void ChooseWife(){
myWife = Wife.GetInstance();
myWife.Show();
}
public void GetMarry(){
myWife = Wife.GetInstance();
myWife.Marry();
}
}
Wife类:Wife.class:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Wife {
static Lock lock = new ReentrantLock();
private static Wife wife;
private Wife(){};
public static Wife GetInstance(){
if(wife==null){
lock.lock();
if(wife==null){
wife = new Wife();
}
lock.unlock();
}
return wife;
}
public void Show() {
// TODO Auto-generated constructor stub
System.out.println("漂亮的本姑娘出来展示自己了哈,来看看我有多美");
}
public void Marry() {
// TODO Auto-generated method stub
System.out.println("漂亮的本姑娘跟喜欢的男青年结婚了");
}
}
Mother类:Mother.class:
public class Mother {
Wife daughterView = null;
public void CheckDaughterView(){
daughterView = Wife.GetInstance();
daughterView.Show();
}
}
5,运行结果:
大龄男青年挑选了一个漂亮姑娘
漂亮的本姑娘出来展示自己了哈,来看看我有多美
大龄男青年觉得不错,决定跟漂亮姑娘去结婚
漂亮的本姑娘跟喜欢的男青年结婚了
大龄男青年的母亲想要见见媳妇
漂亮的本姑娘出来展示自己了哈,来看看我有多美