概述
创建型模式主要有单例模式、简单工厂模式、工厂方法模式、抽象工厂模式、建造者模式、原型模式
这里主要讲单例模式和三种工厂模式
单例模式
- 导图
类图
1.类图分为三部分,依次是类名、属性、方法
2.以<>结尾的为注释信息
3.修饰符+代表public,-代表private,#代表protected,什么都没有代表包可见。
4.带下划线的属性或方法代表是静态的。
- 实现代码1(饿汉式单例):
/** * 描述:单例模式 * 通用代码:(是线程安全的) */public class Singleton { private static final Singleton singleton = new Singleton(); //限制产生多个对象 private Singleton(){ } //通过该方法获得实例对象 public static Singleton getSingleton(){ return singleton; } //类中其他方法,尽量是static public static void doSomething(){ System.out.println(singleton.hashCode()); }}
- 实现代码2(懒汉式单例):
/** * 描述:单例模式 线程不安全实例 */public class SingletonInstance { private static SingletonInstance singleton = null; //限制产生多个对象 private SingletonInstance(){ } //通过该方法获得实例对象 这个方法不是线程安全的,需要加synchronized public static SingletonInstance getInstance(){ if(singleton == null){ singleton = new SingletonInstance(); } return singleton; } //类中其他方法,尽量是static public static void doSomething(){ System.out.println(singleton.hashCode()); }}
上述两种方式都可实现单例模式,但是需要代码2不是线程安全的,使用的时候需要注意
- 单例模式的应用
Spring中的Bean,默认就是单例模式
JDK中体现:
(1)Runtime
(2)NumberFormat
类图:
工厂方法模式/简单工厂模式
- 结构图
/** * 描述:运算的基类 */public abstract class Operation { public abstract int getResult();}/** * 描述:加法类 */public class OperationAdd extends Operation { int a,b; public OperationAdd(int a, int b) { this.a = a; this.b = b; } @Override public int getResult() { return a + b; }}/** * 描述:减法类 */public class OperationSub extends Operation { int a,b; public OperationSub(int a, int b) { this.a = a; this.b = b; } @Override public int getResult() { return a - b; }}/** * 描述:计算器(工厂类) */public class OperationFactory { public Operation createOperation(String opt, int a, int b) { Operation operation = null; switch (opt){ case "+": operation = new OperationAdd(a, b); break; case "-": operation = new OperationSub(a, b); break; } return operation; }}
- JKD中的应用
Collection中的iterator方法
抽象工厂模式
閱讀更多 煙火式java 的文章