首页 > 编程语言 >在Java中23种设计模式,分类以及代码示例

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

时间:2024-09-03 09:53:27浏览次数:11  
标签:Java 示例 void 模式 public new operation 设计模式 class

在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
    

标签:Java,示例,void,模式,public,new,operation,设计模式,class
From: https://blog.csdn.net/qq_38105536/article/details/141822963

相关文章