单例模式(饿汉式)
public class Singleton1 { // 私有构造 private Singleton1() {} private static Singleton1 single = new Singleton1(); // 静态工厂方法 public static Singleton1 getInstance() { return single; } }
单例模式(懒汉式,兼顾线程安全与效率)
public class Singleton4 { // 私有构造 private Singleton4() {} private static Singleton4 single = null; // 双重检查 public static Singleton4 getInstance() { if (single == null) { synchronized (Singleton4.class) { if (single == null) { single = new Singleton4(); } } } return single; } }
工厂模式
public abstract class NoodlesFactory {
public abstract INoodles create();
}
- 1
- 2
- 3
兰州拉面工厂 (具体工厂子类):
public class LzFactory extends NoodlesFactory {
@Override
public INoodles create() {
return new LzNoodles();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
泡面工厂 (具体工厂子类):
public class PaoFactory extends NoodlesFactory {
@Override
public INoodles create() {
return new PaoNoodles();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
最爱的干扣面工厂 (具体工厂子类):
public class GankouFactory extends NoodlesFactory {
@Override
public INoodles create() {
return new GankouNoodles();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
使用时:
/**
* 普通工厂方法:
*/
System.out.println("===========================普通工厂方法==============================" +
"\n 这种要多写一个类,不过更面向对象吧 = = ,实际中我更倾向于使用【模仿Executor类】的方式");
NoodlesFactory factory1 = new GankouFactory();
INoodles gk3 = factory1.create();
gk3.desc();