在Java中23种设计模式,分类以及代码示例

在Java中23种设计模式,分类以及代码示例

在Java中,设计模式可以分为23种,以三个不同的分类进行划分。

1. 创建型模式(Creational Patterns):

  • 单例模式(Singleton)
  • 原型模式(Prototype)
  • 工厂方法模式(Factory Method)
  • 抽象工厂模式(Abstract Factory)
  • 建造者模式(Builder)

2. 结构型模式(Structural Patterns):

  • 适配器模式(Adapter)
  • 桥接模式(Bridge)
  • 组合模式(Composite)
  • 装饰器模式(Decorator)
  • 外观模式(Facade)
  • 享元模式(Flyweight)
  • 代理模式(Proxy)

3. 行为型模式(Behavioral Patterns):

  • 模板方法模式(Template Method)
  • 命令模式(Command)
  • 迭代器模式(Iterator)
  • 观察者模式(Observer)
  • 中介者模式(Mediator)
  • 备忘录模式(Memento)
  • 解释器模式(Interpreter)
  • 状态模式(State)
  • 策略模式(Strategy)
  • 职责链模式(Chain of Responsibility)
  • 访问者模式(Visitor)

这些设计模式各自具有不同的目的和应用场景,可以帮助开发者解决各种不同的问题,并提供良好的代码结构和可维护性。

下面将列出这些设计模式,每个设计模式都附带一个简单的代码示例。

  1. 创建型模式(Creational Patterns)
  • 工厂方法模式(Factory Method Pattern):

    interface Product {
        void operation();
    }
    
    class ConcreteProduct implements Product {
        @Override
        public void operation() {
            System.out.println("ConcreteProduct operation");
        }
    }
    
    abstract class Creator {
        public abstract Product createProduct();
    }
    
    class ConcreteCreator extends Creator {
        @Override
        public Product createProduct() {
            return new ConcreteProduct();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Creator creator = new ConcreteCreator();
            Product product = creator.createProduct();
            product.operation();
        }
    }
    
    • 抽象工厂模式(Abstract Factory Pattern):
    interface AbstractProductA {
        void operation();
    }
    
    interface AbstractProductB {
        void operation();
    }
    
    class ConcreteProductA1 implements AbstractProductA {
        @Override
        public void operation() {
            System.out.println("ConcreteProductA1 operation");
        }
    }
    
    class ConcreteProductB1 implements AbstractProductB {
        @Override
        public void operation() {
            System.out.println("ConcreteProductB1 operation");
        }
    }
    
    interface AbstractFactory {
        AbstractProductA createProductA();
        AbstractProductB createProductB();
    }
    
    class ConcreteFactory1 implements AbstractFactory {
        @Override
        public AbstractProductA createProductA() {
            return new ConcreteProductA1();
        }
    
        @Override
        public AbstractProductB createProductB() {
            return new ConcreteProductB1();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            AbstractFactory factory = new ConcreteFactory1();
            AbstractProductA productA = factory.createProductA();
            AbstractProductB productB = factory.createProductB();
            productA.operation();
            productB.operation();
        }
    }
    
    • 单例模式(Singleton Pattern):
    class Singleton {
        private static Singleton instance;
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Singleton singleton = Singleton.getInstance();
        }
    }
    
  1. 结构型模式(Structural Patterns)

    • 适配器模式(Adapter Pattern):
    interface Target {
        void operation();
    }
    
    class Adaptee {
        void specificOperation() {
            System.out.println("Specific operation");
        }
    }
    
    class Adapter implements Target {
        private Adaptee adaptee;
    
        Adapter(Adaptee adaptee) {
            this.adaptee = adaptee;
        }
    
        @Override
        public void operation() {
            adaptee.specificOperation();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Adaptee adaptee = new Adaptee();
            Target target = new Adapter(adaptee);
            target.operation();
        }
    }
    
    • 桥接模式(Bridge Pattern):
    interface Implementor {
        void operationImpl();
    }
    
    class ConcreteImplementorA implements Implementor {
        @Override
        public void operationImpl() {
            System.out.println("ConcreteImplementorA operationImpl");
        }
    }
    
    class ConcreteImplementorB implements Implementor {
        @Override
        public void operationImpl() {
            System.out.println("ConcreteImplementorB operationImpl");
        }
    }
    
    abstract class Abstraction {
        protected Implementor implementor;
    
        public Abstraction(Implementor implementor) {
            this.implementor = implementor;
        }
    
        abstract void operation();
    }
    
    class RefinedAbstraction extends Abstraction {
        public RefinedAbstraction(Implementor implementor) {
            super(implementor);
        }
    
        @Override
        void operation() {
            implementor.operationImpl();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Implementor implementorA = new ConcreteImplementorA();
            Implementor implementorB = new ConcreteImplementorB();
    
            Abstraction abstractionA = new RefinedAbstraction(implementorA);
            abstractionA.operation();
    
            Abstraction abstractionB = new RefinedAbstraction(implementorB);
            abstractionB.operation();
        }
    }
    
    • 组合模式(Composite Pattern):
    import java.util.ArrayList;
    import java.util.List;
    
    abstract class Component {
        protected String name;
    
        public Component(String name) {
            this.name = name;
        }
    
        abstract void operation();
    }
    
    class Leaf extends Component {
        public Leaf(String name) {
            super(name);
        }
    
        @Override
        void operation() {
            System.out.println("Leaf " + name + " operation");
        }
    }
    
    class Composite extends Component {
        private List<Component> children = new ArrayList<>();
    
        public Composite(String name) {
            super(name);
        }
    
        public void add(Component component) {
            children.add(component);
        }
    
        public void remove(Component component) {
            children.remove(component);
        }
    
        @Override
        void operation() {
            System.out.println("Composite " + name + " operation");
            for (Component component : children) {
                component.operation();
            }
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Component leaf1 = new Leaf("leaf1");
            Component leaf2 = new Leaf("leaf2");
            Component leaf3 = new Leaf("leaf3");
    
            Component composite1 = new Composite("composite1");
            Component composite2 = new Composite("composite2");
    
            composite1.add(leaf1);
            composite1.add(leaf2);
    
            composite2.add(composite1);
            composite2.add(leaf3);
    
            composite2.operation();
        }
    }
    
  2. 行为型模式(Behavioral Patterns)

    • 观察者模式(Observer Pattern):
    import java.util.ArrayList;
    import java.util.List;
    
    interface Observer {
        void update(String message);
    }
    
    class ConcreteObserver implements Observer {
        private String name;
    
        public ConcreteObserver(String name) {
            this.name = name;
        }
    
        @Override
        public void update(String message) {
            System.out.println(name + " received message: " + message);
        }
    }
    
    interface Subject {
        void attach(Observer observer);
        void detach(Observer observer);
        void notifyObservers(String message);
    }
    
    class ConcreteSubject implements Subject {
        private List<Observer> observers = new ArrayList<>();
    
        @Override
        public void attach(Observer observer) {
            observers.add(observer);
        }
    
        @Override
        public void detach(Observer observer) {
            observers.remove(observer);
        }
    
        @Override
        public void notifyObservers(String message) {
            for (Observer observer : observers) {
                observer.update(message);
            }
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            ConcreteSubject subject = new ConcreteSubject();
    
            Observer observer1 = new ConcreteObserver("Observer1");
            Observer observer2 = new ConcreteObserver("Observer2");
    
            subject.attach(observer1);
            subject.attach(observer2);
    
            subject.notifyObservers("Hello");
        }
    }
    
    • 策略模式(Strategy Pattern):
    interface Strategy {
        void execute();
    }
    
    class ConcreteStrategyA implements Strategy {
        @Override
        public void execute() {
            System.out.println("ConcreteStrategyA execute");
        }
    }
    
    class ConcreteStrategyB implements Strategy {
        @Override
        public void execute() {
            System.out.println("ConcreteStrategyB execute");
        }
    }
    
    class Context {
        private Strategy strategy;
    
        public void setStrategy(Strategy strategy) {
            this.strategy = strategy;
        }
    
        public void executeStrategy() {
            strategy.execute();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Context context = new Context();
    
            Strategy strategyA = new ConcreteStrategyA();
            context.setStrategy(strategyA);
            context.executeStrategy();
    
            Strategy strategyB = new ConcreteStrategyB();
            context.setStrategy(strategyB);
            context.executeStrategy();
        }
    }
    
    • 命令模式(Command Pattern):
    interface Command {
        void execute();
    }
    
    class Receiver {
        void action() {
            System.out.println("Receiver action");
        }
    }
    
    class ConcreteCommand implements Command {
        private Receiver receiver;
    
        public ConcreteCommand(Receiver receiver) {
            this.receiver = receiver;
        }
    
        @Override
        public void execute() {
            receiver.action();
        }
    }
    
    class Invoker {
        private Command command;
    
        public void setCommand(Command command) {
            this.command = command;
        }
    
        public void executeCommand() {
            command.execute();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Receiver receiver = new Receiver();
            Command command = new ConcreteCommand(receiver);
    
            Inv
    
  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小七蒙恩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值