java常用设计模式总结

4,736 阅读4分钟

设计模式总结

本篇文章不对每一个设计模式进行细讲,只对常见的设计模式展开。如有不对,感谢指正。

一、分类:

  • 创建型模式:工厂方法模式、抽象工厂模式单例、建造者、原型模式
  • 结构型模式:适配器、装饰器、代理、外观、桥接、组合、享元模式
  • 行为型模式:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式

二、创建型模式

2、1 单例模式

分为懒汉式和饿汉模式

  • 饿汉式:在使用前就创建好实例
public class Singleton {

    public static Singleton instance=new Singleton();

    private Singleton(){

    }

    public static Singleton getInstance() {
        return instance;
    }
}
  • 懒汉式:使用到才创建实例
public class Singleton {

    public static volatile Singleton instance;

    private Singleton() {

    }

    public static Singleton getInstance() {
        if (instance == null) {
            // 双重检查锁
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

2、2 简单工厂模式

工厂创建实例,而这些实例都实现了同一个接口,通过传递给不同的参数给工厂,工厂以此来创建不同的实例。 例子: 实体类:水果

@Data
public class Fruit {
    
    private String name;
    private String color;
    
}
@Data
public class Apple extends Fruit {
    
}
@Data
public class Orange extends Fruit {
}

接口类:

public interface FruitService {

    String getFruitName();


}

实现类:拿AppleService为例子

public class AppleService implements FruitService {


   @Override
    public String getFruitName() {
        return "apple";
    }
}

工厂类:

public class SimpleFruitFactory {

    public FruitService getFruit(String name) {
        if ("apple".equals(name)) {
            return new AppleService();
        } else if ("orange".equals(name)) {
            return new OrangeService();
        } else {
            return null;
        }

    }

    public static void main(String[] args) {
        SimpleFruitFactory factory = new SimpleFruitFactory();
        System.out.println("the name is " + factory.getFruit("apple").getFruitName());
    }

}

2、3 多工厂模式

即一个工厂中提供多个工厂方法

2、4 抽象工厂模式模式

创建多个工厂类

2、5 建造者模式

通过不同方法来创建复合对象。 实例:

public class BuilderDemo {

    public static People builder() {
        return new People();
    }

    @Data
    static class People {
        private String name;
        private int age;

        public People setPeopleName(String name) {
            this.setName(name);
            return this;
        }

        public People setPeopleAge(int age) {
            this.setAge(age);
            return this;
        }

        public void build() {
            System.out.println(this.toString());
        }
    }

    public static void main(String[] args) {
        BuilderDemo.builder()
                .setPeopleName("小明")
                .setPeopleAge(10)
                .build();
    }

}

三、结构型模式

3、1 适配器模式

将类或接口转换为期望的形式表示,已达到兼容的效果。主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。

  • 类的适配器模式:通过继承目标类,实现扩展的接口类(该类包含目标类相同的方法)

    目标类:

  public class TargeClass {

    public void say() {
        System.out.println("hello world");
    }

    }

实现扩展的接口类


    public interface Compatible {
    
        void say();
    
        void bye();
    }

public class ClassAdapter extends TargeClass implements Compatible{
    
    @Override
    public void bye() {
        System.out.println("bye");
    }

    public static void main(String[] args) {
        ClassAdapter classAdapter = new ClassAdapter();
        classAdapter.say();
        classAdapter.bye();
    }
}

  • 对象的适配器模式 适配器类不继承目标类,而是持有目标类对象

public class WrapperAdapter implements Compatible {

    private TargeClass targeClass;

    public WrapperAdapter(TargeClass targeClass) {
        this.targeClass = targeClass;
    }

    @Override
    public void say() {

    }

    @Override
    public void bye() {

    }
}

  • 接口的适配器模式

    一个接口中有多个方法需要实现,但是并不是所有的都是需要的,这时可以借助于一个抽象类, 该抽象类实现了该接口, 实现了所有的方法, 不和原始的接口打交道,只和该抽象类取得联系,所以写一个类,继承该抽象类,重写需要的方法

3、1 装饰模式

动态地为对象添加一些新的功能,装饰器持有被装饰类的对象,装饰器和被装饰的类实现相同的接口。 例子:

接口

public interface Decorable {

    void doSomethings();

}

被装饰的类:

public class Target implements Decorable {
    @Override
    public void doSomethings() {
        System.out.println("Target doSomethings");
    }
}

装饰器:

public class Decorator implements Decorable {

    private Target target;

    public Decorator(Target target) {
        super();
        this.target = target;
    }

    @Override
    public void doSomethings() {
        System.out.println("before decorate");
        target.doSomethings();
        System.out.println("after decorate");
    }

    public static void main(String[] args) {
        Decorable decorable = new Decorator(new Target());
        decorable.doSomethings();
    }
}

四、行为型模式

4、1 策略模式

定义多个算法,有外部用户决定使用哪个算法,实现接口方法。

接口类:

public interface ICalculator {

    int calculate(int a, int b);
}

实现类:

public class Plus implements ICalculator {
    @Override
    public int calculate(int a, int b) {
        return a + b;
    }
}
public class Subtraction implements ICalculator {
    @Override
    public int calculate(int a, int b) {
        return a - b;
    }
}

实例测试:

public class StrategyTest {

    public static void main(String[] args) {
        ICalculator plus = new Plus();
        System.out.println(plus.calculate(1,2));
    }
}

4、2 观察者模式

观察者向主题发起订阅,当主题发生改变时,会通知观察者。

定义观察者接口:

public interface Observer {

    void notifyNotice();

}

观察者:

public class Observer1 implements Observer {
    @Override
    public void notifyNotice() {
        System.out.println("1 had receive notices");
    }
}
public class Observer2 implements Observer {
    @Override
    public void notifyNotice() {
        System.out.println("2 had receive notices");
    }
}

主题:

public class Subject {

    private List<Observer> observerList = new ArrayList();

    public void add(Observer observer) {
        observerList.add(observer);
    }

    public void notifyAllObserver() {
        for (Observer observer : observerList) {
            observer.notifyNotice();
        }
    }

}

测试:

public class ObserverTest {

    public static void main(String[] args) {
        Subject subject = new Subject();
        subject.add(new Observer1());
        subject.add(new Observer2());
        subject.notifyAllObserver();
    }
}

其他

个人博客