在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例
单例模式三要素:
- 私有构造方法
- 指向自己实例的私有静态引用
- 以自己实例为返回值的静态公有方法
饿汉式
public class Hungrey {
private static Hungrey hungrey = new Hungrey();
private Hungrey() {
}
public static Hungrey getHungrey(){
return hungrey;
}
}
懒汉式
懒汉式是非线程安全的,可以在方法上加synchronized 保证线程安全
也可以用双重校验锁的形式
public class Lazy {
private static Lazy lazy=null;
private Lazy() {
}
//可以加synchronized
public static Lazy getLazy(){
//双重校验锁
if (lazy ==null){
synchronized (Lazy.class){
if (lazy==null){
return new Lazy();
}
}
}
return lazy;
}
}
创建线程来验证结果:
public class MyThread extends Thread {
static Set<Lazy> sets = new HashSet<Lazy>();
@Override
public void run() {
sets.add(Lazy.getLazy());
}
}
@Test
public void demo(){
for( int i = 1; i <= 1000 ; i++ ){
new MyThread().start();
}
System.out.println(MyThread.sets);
}
如果没加同步锁,懒汉式的set集合中是会出现两个对象的(多跑几次,总会有出现的)
抽象工厂模式
总工厂
public interface CarFactory {
Seat createSeat();
Wheel createWheel();
}
便宜工厂
public class LowFactory implements CarFactory {
@Override
public Seat createSeat() {
return new LowSeat();
}
@Override
public Wheel createWheel() {
return new LowWheel();
}
}
高级工厂
public class LuxuryFactory implements CarFactory{
@Override
public Seat createSeat() {
return new LuxurySeat();
}
@Override
public Wheel createWheel() {
return new LuxuryWheel();
}
}
方向盘接口
public interface Wheel {
String message();
}
座椅接口
public interface Seat {
String message();
}
高级方向盘
public class LuxuryWheel implements Wheel {
@Override
public String message() {
return "真皮方向盘";
}
}
高级座椅
public class LuxurySeat implements Seat {
@Override
public String message() {
return "豪华真皮软座";
}
}
便宜方向盘
public class LowWheel implements Wheel{
@Override
public String message() {
return "垃圾方向盘";
}
}
便宜座椅
public class LowSeat implements Seat {
@Override
public String message() {
return "硬座";
}
}
测试:
@Test
public void demo1(){
CarFactory luxuryFactory = new LuxuryFactory();
Wheel wheel = luxuryFactory.createWheel();
System.out.println(wheel.message());
Assert.assertEquals(wheel.message(),"真皮");
}