-
单例模式
-
线程不安全
public class Sinfleton{ private static Singleton instance; private Singleton(){} public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; } }
-
线程安全
-
getInstance()用synchroniz进行修饰。
- 由于getInstance ()方法使用率低,对程序性能不关键;
- 加锁影响效率
-
引进Singleton类时即构建其单例
-
不用加锁效率较高
-
易产生垃圾对象
-
加载时初始化浪费内存
public class Singleton{ private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } }
-
-
双重校验锁(DCL double-checked locking),只在创建单例时加锁
-
双锁机制在多线程下保持高性能
public class Singleton{ private Singleton instance; private Singleton()}{} public static Singleton getInstance(){ if (instance == null){ synchronized(Singleton.class){ if(istance == null){ instance = new Singleton(); } } } return instance; } }
-
-
采用holder保证初始化时只有一个线程
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
-
-
-
工厂模式:定义接口,使产品类全部继承该接口并重写关键函数,然后根据不同条件创建不同实例,返回对应父类类型的产品
-
优点:调用者只需知道产品名称就可以创建对应的对象、拓展新高、忽略产品具体实现,只需要关心产品的接口
-
缺点:对每种产品都需要添加相应的产品类和对象实现工厂,增加了系统复杂度与具体类的依赖
-
适用于需要生成复杂对象的地方,对于简单对象,直接new即可,不需要引入工厂类增加系统复杂度
//接口 public interface Shape{ void draw(); } //实体类 public class Circle implements Shape{ @Override public void draw(){ sout("draw circle"); } } public class Square implements Shape{ @Override public void draw(){ sout("draw square"); } } //工厂 public class Shapefactory{ public Shape getShape(String type){ if(type == null){ return null; } if(type.equals("Circle")){return new Circle;} else if(type.equals("Square")){return new Square;} return null; } } //使用工厂 public class FactoryDemo{ public static void main(String[] args){ ShapeFactory sf = new ShapeFactory(); Shape shape1 = sf.getShape("Circle"); Shape shape2 = sf.getShpae("Square"); } }
-
-
建造者模式:多个简单对象构成复杂对象,如StringBuilder
- 优点:创建者独立,易拓展,便于控制细节风险
- 缺点:产品范围有限制,必须有共同点、生成对象内部属性相互依赖
-
适配器模式
-
观察者模式:对象间一对多关系时,若一个对象状态发生改变,则所有依赖其的对象都被通知并更新
- 优点:观察者与被观察者关系是抽象耦合的,触发机制
- 缺点:一对很多观察者时,通知所有观察者会花费很多时间、循环依赖可能导致系统崩溃、观察者只能知道被观察者发生变化而不知道如何变化
-
桥接模式
网友评论