在 Java 开发中,设计模式是常用的解决方案,用于解决软件设计中的常见问题。以下是一些常用的设计模式:
创建型模式(Creational Patterns)
-
单例模式(Singleton Pattern):
- 确保一个类只有一个实例,并提供一个全局访问点。
- 示例:
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
-
工厂方法模式(Factory Method Pattern):
- 定义一个接口用于创建对象,但让子类决定实例化哪个类。
- 示例:
public interface Product { void use(); } public class ConcreteProduct implements Product { public void use() { System.out.println("Using ConcreteProduct"); } } public abstract class Creator { public abstract Product createProduct(); } public class ConcreteCreator extends Creator { public Product createProduct() { return new ConcreteProduct(); } }
-
抽象工厂模式(Abstract Factory Pattern):
- 提供一个接口,用于创建相关或依赖对象的家族,而不指定具体类。
- 示例:
public interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); } public class ConcreteFactory1 implements AbstractFactory { public ProductA createProductA() { return new ProductA1(); } public ProductB createProductB() { return new ProductB1(); } }
-
建造者模式(Builder Pattern):
- 将对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。
- 示例:
public class Product { private String part1; private String part2; public void setPart1(String part1) { this.part1 = part1; } public void setPart2(String part2) { this.part2 = part2; } } public abstract class Builder { protected Product product = new Product(); public abstract void buildPart1(); public abstract void buildPart2(); public Product getResult() { return product; } } public class ConcreteBuilder extends Builder { public void buildPart1() { product.setPart1("Part1"); } public void buildPart2() { product.setPart2("Part2"); } }
-
原型模式(Prototype Pattern):
- 用于创建重复对象,同时又能保证性能。
- 示例:
public class Prototype implements Cloneable { public Prototype clone() throws CloneNotSupportedException { return (Prototype) super.clone(); } }
结构型模式(Structural Patterns)
-
适配器模式(Adapter Pattern):
- 将一个类的接口转换成客户希望的另一个接口。
- 示例:
public interface Target { void request(); } public class Adaptee { public void specificRequest() { System.out.println("Specific request"); } } public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } }
-
桥接模式(Bridge Pattern):
- 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
- 示例:
public abstract class Abstraction { protected Implementor implementor; protected Abstraction(Implementor implementor) { this.implementor = implementor; } public abstract void operation(); } public interface Implementor { void operationImpl(); } public class ConcreteImplementorA implements Implementor { public void operationImpl() { System.out.println("ConcreteImplementorA operation"); } } public class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor implementor) { super(implementor); } public void operation() { implementor.operationImpl(); } }
-
组合模式(Composite Pattern):
- 允许你将对象组合成树形结构来表现"整体/部分"层次结构。
- 示例:
public abstract class Component { public void add(Component component) {} public void remove(Component component) {} public Component getChild(int i) { return null; } public abstract void operation(); } public class Leaf extends Component { public void operation() { System.out.println("Leaf operation"); } } public class Composite extends Component { private List<Component> children = new ArrayList<>(); public void add(Component component) { children.add(component); } public void remove(Component component) { children.remove(component); } public Component getChild(int i) { return children.get(i); } public void operation() { for (Component child : children) { child.operation(); } } }
-
装饰模式(Decorator Pattern):
- 动态地给对象添加一些额外的职责。
- 示例:
public interface Component { void operation(); } public class ConcreteComponent implements Component { public void operation() { System.out.println("ConcreteComponent operation"); } } public class Decorator implements Component { protected Component component; public Decorator(Component component) { this.component = component; } public void operation() { component.operation(); } } public class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } public void operation() { super.operation(); addedBehavior(); } public void addedBehavior() { System.out.println("ConcreteDecorator added behavior"); } }
-
外观模式(Facade Pattern):
- 提供一个统一的接口,用来访问子系统中的一群接口。
- 示例:
public class Facade { private Subsystem1 subsystem1 = new Subsystem1(); private Subsystem2 subsystem2 = new Subsystem2(); public void operation() { subsystem1.operation(); subsystem2.operation(); } } public class Subsystem1 { public void operation() { System.out.println("Subsystem1 operation"); } } public class Subsystem2 { public void operation() { System.out.println("Subsystem2 operation"); } }
-
享元模式(Flyweight Pattern):
- 使用共享对象来减少内存消耗。
- 示例:
public class Flyweight { private String intrinsicState; public Flyweight(String intrinsicState) { this.intrinsicState = intrinsicState; } public void operation(String extrinsicState) { System.out.println("Intrinsic State = " + intrinsicState + ", Extrinsic State = " + extrinsicState); } } public class FlyweightFactory { private Map<String, Flyweight> flyweights = new HashMap<>(); public Flyweight getFlyweight(String key) { if (!flyweights.containsKey(key)) { flyweights.put(key, new Flyweight(key)); } return flyweights.get(key); } }
-
代理模式(Proxy Pattern):
- 为其他对象提供一种代理以控制对这个对象的访问。
- 示例:
public interface Subject { void request(); } public class RealSubject implements Subject { public void request() { System.out.println("RealSubject request"); } } public class Proxy implements Subject { private RealSubject realSubject; public void request() { if (realSubject == null) { realSubject = new RealSubject(); } realSubject.request(); } }
行为型模式(Behavioral Patterns)
-
责任链模式(Chain of Responsibility Pattern):
- 为请求创建一个处理链。
- 示例:
public abstract class Handler { protected Handler successor; public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handleRequest(String request); } public class ConcreteHandler1 extends Handler { public void handleRequest(String request) { if (request.equals("Request1")) { System.out.println("ConcreteHandler1 handled the request"); } else if (successor != null) { successor.handleRequest(request); } } } public class ConcreteHandler2 extends Handler { public void handleRequest(String request) { if (request.equals("Request2")) { System.out.println("ConcreteHandler2 handled the request"); } else if (successor != null) { successor.handleRequest(request); } } }
-
命令模式(Command Pattern):
- 将请求封装成对象,从而使您可以用不同的请求对客户进行参数化。
// 定义命令接口
public interface Command {
void execute();
}
// 具体命令类
public class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
public void execute() {
receiver.action();
}
}
// 接收者类
public class Receiver {
public void action() {
System.out.println("Receiver is performing an action");
}
}
// 调用者类
public class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void executeCommand() {
command.execute();
}
}
// 测试类
public class CommandPatternExample {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
invoker.setCommand(command);
invoker.executeCommand();
}
}
在这个例子中:
Command
接口定义了命令的执行方法execute()
。ConcreteCommand
是Command
接口的具体实现,持有一个Receiver
实例用于执行具体操作。Receiver
类执行实际的操作。Invoker
类持有一个Command
对象,并在适当的时候调用Command
的execute()
方法。CommandPatternExample
类展示了如何使用命令模式:创建Receiver
、ConcreteCommand
和Invoker
对象,并将命令分派给调用者执行。
这个例子演示了命令模式如何将请求封装成对象,从而使得请求的发送者和接收者解耦,同时支持撤销和重做操作。
-
解释器模式(Interpreter Pattern):
- 给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
- 示例:
public interface Expression { int interpret(); } public class NumberExpression implements Expression { private int number; public NumberExpression(int number) { this.number = number; } public int interpret() { return number; } } public class AddExpression implements Expression { private Expression left; private Expression right; public AddExpression(Expression left, Expression right) { this.left = left; this.right = right; } public int interpret() { return left.interpret() + right.interpret(); } }
-
迭代器模式(Iterator Pattern):
- 提供一种方法顺序访问一个聚合对象中的各个元素,而不暴露其内部表示。
- 示例:
public interface Iterator<T> { boolean hasNext(); T next(); } public interface Aggregate { Iterator<String> createIterator(); } public class ConcreteAggregate implements Aggregate { private String[] items = {"A", "B", "C"}; public Iterator<String> createIterator() { return new ConcreteIterator(items); } } public class ConcreteIterator implements Iterator<String> { private String[] items; private int position = 0; public ConcreteIterator(String[] items) { this.items = items; } public boolean hasNext() { return position < items.length; } public String next() { return items[position++]; } }
-
中介者模式(Mediator Pattern):
- 用一个中介对象来封装一系列的对象交互。
- 示例:
public interface Mediator { void notify(Component sender, String event); } public class ConcreteMediator implements Mediator { private Component component1; private Component component2; public void setComponent1(Component component1) { this.component1 = component1; } public void setComponent2(Component component2) { this.component2 = component2; } public void notify(Component sender, String event) { if (sender == component1) { component2.handleEvent(event); } else if (sender == component2) { component1.handleEvent(event); } } } public abstract class Component { protected Mediator mediator; public Component(Mediator mediator) { this.mediator = mediator; } public abstract void handleEvent(String event); } public class ConcreteComponent1 extends Component { public ConcreteComponent1(Mediator mediator) { super(mediator); } public void handleEvent(String event) { System.out.println("ConcreteComponent1 handled event: " + event); mediator.notify(this, event); } } public class ConcreteComponent2 extends Component { public ConcreteComponent2(Mediator mediator) { super(mediator); } public void handleEvent(String event) { System.out.println("ConcreteComponent2 handled event: " + event); mediator.notify(this, event); } }
-
备忘录模式(Memento Pattern):
- 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
- 示例:
public class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } } public class Originator { private String state; public void setState(String state) { this.state = state; } public Memento saveStateToMemento() { return new Memento(state); } public void getStateFromMemento(Memento memento) { state = memento.getState(); } } public class Caretaker { private Memento memento; public void setMemento(Memento memento) { this.memento = memento; } public Memento getMemento() { return memento; } }
-
观察者模式(Observer Pattern):
- 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。
- 示例:
public interface Observer { void update(String message); } public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(String message); } public class ConcreteSubject implements Subject { private List<Observer> observers = new ArrayList<>(); public void registerObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); } public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } } public class ConcreteObserver implements Observer { public void update(String message) { System.out.println("Received message: " + message); } }
-
状态模式(State Pattern):
- 允许对象在内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
- 示例:
public interface State { void handle(); } public class ConcreteStateA implements State { public void handle() { System.out.println("Handling with State A"); } } public class ConcreteStateB implements State { public void handle() { System.out.println("Handling with State B"); } } public class Context { private State currentState; public void setState(State state) { this.currentState = state; } public void request() { currentState.handle(); } }
这些设计模式在 Java 开发中广泛应用,通过不同的模式可以解决各种不同的设计问题,提高代码的灵活性、可维护性和可扩展性。
标签:Java,String,void,Component,private,class,熟悉,设计模式,public From: https://blog.csdn.net/weixin_45990682/article/details/140093097