设计模式(Design Pattern)是一套被反复使用、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被理解、提高代码的可靠性。
- //创建接口
- public interface Shape {
- void draw();
- }
-
- //具体实体类
- public class Rectangle implements Shape {
- @Override
- public void draw() {
- System.out.println("Inside Rectangle::draw() method.");
- }
- }
-
- public class Square implements Shape {
- @Override
- public void draw() {
- System.out.println("Inside Square::draw() method.");
- }
- }
-
- //创建工厂生成具体实例
- @Component
- public class ShapeFactory {
- private Map
shapeMap = new HashMap<>(); -
- public ShapeFactory() {
- shapeMap.put("CIRCLE", new Circle());
- shapeMap.put("RECTANGLE", new Rectangle());
- shapeMap.put("SQUARE", new Square());
- }
-
- public Shape getShape(String shapeType){
- return shapeMap.get(shapeType);
- }
- }
- //创建接口
- public interface Animal {
- void speak();
- }
-
- //具体实体类
- public class Dog implements Animal {
- @Override
- public void speak() {
- System.out.println("Woof!");
- }
- }
-
- public class Cat implements Animal {
- @Override
- public void speak() {
- System.out.println("Meow!");
- }
- }
-
- //抽象工厂
- public abstract AnimalFactory {
- public abstract Animal createAnimal();
- }
-
- //创建实现该抽象工厂类的具体工厂类:
- public class DogFactory extends AnimalFactory {
- @Override
- public Animal createAnimal() {
- return new Dog();
- }
- }
-
- public class CatFactory extends AnimalFactory {
- @Override
- public Animal createAnimal() {
- return new Cat();
- }
- }
- //饿汉式
- public class Singleton {
- private static Singleton instance = new Singleton();
- private Singleton() {}
- public static Singleton getInstance() {
- return instance;
- }
- }
- //懒汉式
- public class Singleton {
- private static Singleton instance;
- private Singleton() {}
- public static synchronized Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
- //DCL
- public class Singleton {
- private volatile static Singleton instance;
- private Singleton() {}
- public static Singleton getInstance() {
- if (instance == null) { // 第一次检查
- synchronized (Singleton.class) {
- if (instance == null) { // 第二次检查
- instance = new Singleton();
- }
- }
- }
- return instance;