创建型:单例模式、工厂模式、原型模式、建造者模式
结构型:适配器模式、桥接器模式、装饰模式、组合模式、外观模式、享元模式、代理模式
行为型:模版方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式、状态模式、策略模式、职责链模式
创建一个类,创建一个静态方法,根据传进来地字符串创建对象。出啊同方法就是使用if else
或者switch ... case ...
返回要创建地具体对象。例如构造一个生产Pizza的工厂类
保证某个类只能有一个对象,并且提供获取该对象引用的方法。
class Singleton1{
// 在定义时进行初始化
private final static Singleton1 SINGLETON_1 = new Singleton1();
private Singleton1(){}
public static Singleton1 getSingleton(){
return SINGLETON_1;
}
}
或
class Singleton2{
private final static Singleton2 SINGLETON_1;
// 静态代码块
static {
SINGLETON_1 = new Singleton2();
}
private Singleton2(){}
public static Singleton2 getSingleton(){
return SINGLETON_1;
}
}
特点:
public class Lazy1 {
private static Lazy1 instance;
private Lazy1(){}
public static Lazy1 getInstance(){
if(instance == null){
instance = new Lazy1();
}
return instance;
}
}
可以考虑加入synchronized
关键字解决。
class Lazy2{
private static Lazy2 instance;
private Lazy2(){}
public static synchronized Lazy2 getInstance(){
if(instance == null){
instance = new Lazy2();
}
return instance;
}
}
先判断对象是否未创建,然后再加锁减小加锁粒度。
法一:错误示范
class Lazy3{
private static Lazy3 instance;
private Lazy3(){}
public static synchronized Lazy3 getInstance(){
// 线程不安全
if(instance == null){
synchronized (Lazy3.class){
instance = new Lazy3();
}
}
return instance;
}
}
正确做法:使用volatile
关键字,保证修改的可见性
class Lazy3{
// volatile 解决可见性问题
private static volatile Lazy3 instance;
private Lazy3(){}
public static synchronized Lazy3 getInstance(){
if(instance == null){
synchronized (Lazy3.class){
if(instance == null)
instance = new Lazy3();
}
}
return instance;
}
}
getInstance
方法。public final class Singleton {
private Singleton() { }
// 问题1:属于懒汉式还是饿汉式
private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}
// 问题2:在创建时是否有并发问题
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
enum Singleton{
INSTANCE; // 属性
public void method1(){}
}
public static void main(String[] args) {
Singleton lz1 = Singleton.INSTANCE;
lz1.method1();
}
优点:
obj.clone()
。例子:
浅拷贝:
深拷贝可以通过:重写clone方法,或者使用序列化来实现
例如:StringBuilder