java 23种设计模式
- 工厂方法模式 Factory Method
- 抽象工厂模式 Abstract Factory
- 建造者模式 Builder
- 原型模式 Prototype
- 单例模式 Singleton
- 适配器模式 Adapter
- 桥接模式 Bridge
- 组合模式 Composite
- 装饰模式 Decorator
- 外观模式 Facade
- 享元模式 Flyweight
- 代理模式 Proxy
- 解释器模式 Interpreter
- 模板方法模式 Template Method
- 责任链模式 Chain of Responsibility
- 命令模式 Command
- 迭代器模式 Iterator
- 中介者模式 Mediator
- 备忘录模式 Memento
- 观察者模式 Observer
- 状态模式 State
- 策略模式 Strategy
- 访问者模式 Visitor
工厂方法模式 Factory Method
package com.design.patternz;
public class FactoryMethodPattern {
public static void main(String[] args) {
ShapeFactory circleFactory = new CircleFactory();
Shape circle = circleFactory.createShape();
circle.draw();
ShapeFactory rectangleFactory = new RectangleFactory();
Shape rectangle = rectangleFactory.createShape();
rectangle.draw();
}
interface Shape {
void draw();
}
static class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
static class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
static abstract class ShapeFactory {
abstract Shape createShape();
}
static class CircleFactory extends ShapeFactory {
@Override
Shape createShape() {
return new Circle();
}
}
static class RectangleFactory extends ShapeFactory {
@Override
Shape createShape() {
return new Rectangle();
}
}
}
抽象工厂模式 Abstract Factory
package com.design.patternz;
public class AbstractFactoryPattern {
public static void main(String[] args) {
SoftwareFactory windowsFactory = new WindowsFactory();
OperatingSystem windowsOS = windowsFactory.createOperatingSystem();
Application windowsApp = windowsFactory.createApplication();
windowsOS.run();
windowsApp.open();
SoftwareFactory linuxFactory = new LinuxFactory();
OperatingSystem linuxOS = linuxFactory.createOperatingSystem();
Application linuxApp = linuxFactory.createApplication();
linuxOS.run();
linuxApp.open();
}
interface OperatingSystem {
void run();
}
static class WindowsOS implements OperatingSystem {
@Override
public void run() {
System.out.println("Running Windows OS");
}
}
static class LinuxOS implements OperatingSystem {
@Override
public void run() {
System.out.println("Running Linux OS");
}
}
static interface Application {
void open();
}
static class WordApplication implements Application {
@Override
public void open() {
System.out.println("Opening Word Application");
}
}
static class ExcelApplication implements Application {
@Override
public void open() {
System.out.println("Opening Excel Application");
}
}
interface SoftwareFactory {
OperatingSystem createOperatingSystem();
Application createApplication();
}
static class WindowsFactory implements SoftwareFactory {
@Override
public OperatingSystem createOperatingSystem() {
return new WindowsOS();
}
@Override
public Application createApplication() {
return new ExcelApplication();
}
}
static class LinuxFactory implements SoftwareFactory {
@Override
public OperatingSystem createOperatingSystem() {
return new LinuxOS();
}
@Override
public Application createApplication() {
return new WordApplication();
}
}
}
建造者模式 Builder
package com.design.patternz;
public class BuilderPattern {
public static void main(String[] args) {
HouseBuilder concreteBuilder = new ConcreteHouseBuilder();
Director director1 = new Director(concreteBuilder);
House concreteHouse = director1.constructHouse();
System.out.println("Concrete House: " + concreteHouse);
HouseBuilder luxuryBuilder = new LuxuryHouseBuilder();
Director director2 = new Director(luxuryBuilder);
House luxuryHouse = director2.constructHouse();
System.out.println("Luxury House: " + luxuryHouse);
}
static class House {
private String foundation;
private String structure;
private String roof;
private String interior;
public void setFoundation(String foundation) {
this.foundation = foundation;
}
public void setStructure(String structure) {
this.structure = structure;
}
public void setRoof(String roof) {
this.roof = roof;
}
public void setInterior(String interior) {
this.interior = interior;
}
@Override
public String toString() {
return "House [foundation=" + foundation + ", structure=" + structure + ", roof=" + roof + ", interior=" + interior + "]";
}
}
static abstract class HouseBuilder {
protected House house = new House();
public abstract void buildFoundation();
public abstract void buildStructure();
public abstract void buildRoof();
public abstract void buildInterior();
public House getHouse() {
return house;
}
}
static class ConcreteHouseBuilder extends HouseBuilder {
@Override
public void buildFoundation() {
house.setFoundation("Standard Foundation");
}
@Override
public void buildStructure() {
house.setStructure("Standard Structure");
}
@Override
public void buildRoof() {
house.setRoof("Standard Roof");
}
@Override
public void buildInterior() {
house.setInterior("Standard Interior");
}
}
static class LuxuryHouseBuilder extends HouseBuilder {
@Override
public void buildFoundation() {
house.setFoundation("Strong Foundation");
}
@Override
public void buildStructure() {
house.setStructure("Reinforced Structure");
}
@Override
public void buildRoof() {
house.setRoof("Elegant Roof");
}
@Override
public void buildInterior() {
house.setInterior("Luxury Interior");
}
}
static class Director {
private HouseBuilder builder;
public Director(HouseBuilder builder) {
this.builder = builder;
}
public House constructHouse() {
builder.buildFoundation();
builder.buildStructure();
builder.buildRoof();
builder.buildInterior();
return builder.getHouse();
}
}
}
原型模式 Prototype
package com.design.patternz;
public class PrototypePattern {
public static void main(String[] args) {
Shape circle = new Shape("Circle");
Shape clonedCircle = circle.clone();
clonedCircle.setType("Cloned Circle");
System.out.println("Original Shape Type: " + circle.getType());
System.out.println("Cloned Shape Type: " + clonedCircle.getType());
}
static class Shape implements Cloneable {
private String type;
public Shape(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public Shape clone() {
try {
return (Shape) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
}
单例模式 Singleton
package com.design.patternz;
public class SingletonPattern {
private static SingletonPattern instance;
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
if (instance == null) {
instance = new SingletonPattern();
}
return instance;
}
public void showMessage() {
System.out.println("Hello, I am a Singleton!");
}
public static void main(String[] args) {
SingletonPattern singleton = SingletonPattern.getInstance();
singleton.showMessage();
}
}
适配器模式 Adapter
package com.design.patternz;
public class AdapterPattern {
public static void main(String[] args) {
LegacyRectangle legacyRectangle = new LegacyRectangle();
Shape shapeAdapter = new RectangleAdapter(legacyRectangle);
shapeAdapter.draw(10, 20, 50, 30);
}
static class LegacyRectangle {
public void display(int x1, int y1, int x2, int y2) {
System.out.println("LegacyRectangle: Point1(" + x1 + ", " + y1 + "), Point2(" + x2 + ", " + y2 + ")");
}
}
interface Shape {
void draw(int x, int y, int width, int height);
}
static class RectangleAdapter implements Shape {
private LegacyRectangle legacyRectangle;
public RectangleAdapter(LegacyRectangle legacyRectangle) {
this.legacyRectangle = legacyRectangle;
}
@Override
public void draw(int x, int y, int width, int height) {
int x1 = x;
int y1 = y;
int x2 = x + width;
int y2 = y + height;
legacyRectangle.display(x1, y1, x2, y2);
}
}
}
桥接模式 Bridge
package com.design.patternz;
public class BridgePattern {
public static void main(String[] args) {
Color redColor = new Red();
Color blueColor = new Blue();
Shape redCircle = new Circle(redColor);
Shape blueSquare = new Square(blueColor);
redCircle.draw();
blueSquare.draw();
}
interface Color {
void applyColor();
}
static class Red implements Color {
public void applyColor() {
System.out.println("Applying red color");
}
}
static class Blue implements Color {
public void applyColor() {
System.out.println("Applying blue color");
}
}
static abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract void draw();
}
static class Circle extends Shape {
public Circle(Color color) {
super(color);
}
public void draw() {
System.out.print("Drawing a circle. ");
color.applyColor();
}
}
static class Square extends Shape {
public Square(Color color) {
super(color);
}
public void draw() {
System.out.print("Drawing a square. ");
color.applyColor();
}
}
}
组合模式 Composite
package com.design.patternz;
import java.util.ArrayList;
import java.util.List;
public class CompositePattern {
public static void main(String[] args) {
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
Directory subDirectory = new Directory("Subdirectory");
subDirectory.addComponent(file1);
subDirectory.addComponent(file2);
Directory rootDirectory = new Directory("Root");
rootDirectory.addComponent(subDirectory);
rootDirectory.displayInfo();
}
interface FileSystemComponent {
void displayInfo();
}
static class File implements FileSystemComponent {
private String name;
public File(String name) {
this.name = name;
}
public void displayInfo() {
System.out.println("File: " + name);
}
}
static class Directory implements FileSystemComponent {
private String name;
private List<FileSystemComponent> components;
public Directory(String name) {
this.name = name;
components = new ArrayList<>();
}
public void addComponent(FileSystemComponent component) {
components.add(component);
}
public void displayInfo() {
System.out.println("Directory: " + name);
for (FileSystemComponent component : components) {
component.displayInfo();
}
}
}
}
装饰模式 Decorator
package com.design.patternz;
public class DecoratorPattern {
public static void main(String[] args) {
Coffee simpleCoffee = new SimpleCoffee();
System.out.println("Cost: $" + simpleCoffee.cost() + ", Description: " + simpleCoffee.description());
Coffee milkCoffee = new MilkDecorator(simpleCoffee);
System.out.println("Cost: $" + milkCoffee.cost() + ", Description: " + milkCoffee.description());
Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee);
System.out.println("Cost: $" + sugarMilkCoffee.cost() + ", Description: " + sugarMilkCoffee.description());
}
interface Coffee {
double cost();
String description();
}
static class SimpleCoffee implements Coffee {
@Override
public double cost() {
return 2.0;
}
@Override
public String description() {
return "Simple Coffee";
}
}
static abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
@Override
public double cost() {
return decoratedCoffee.cost();
}
@Override
public String description() {
return decoratedCoffee.description();
}
}
static class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return super.cost() + 1.0;
}
@Override
public String description() {
return super.description() + ", with Milk";
}
}
static class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return super.cost() + 0.5;
}
@Override
public String description() {
return super.description() + ", with Sugar";
}
}
}
外观模式 Facade
package com.design.patternz;
public class FacadePattern {
public static void main(String[] args) {
HomeTheaterFacade homeTheater = new HomeTheaterFacade();
homeTheater.watchMovie();
homeTheater.endMovie();
}
static class StereoSystem {
public void turnOn() {
System.out.println("Stereo System is turned on");
}
public void turnOff() {
System.out.println("Stereo System is turned off");
}
}
static class Projector {
public void turnOn() {
System.out.println("Projector is turned on");
}
public void turnOff() {
System.out.println("Projector is turned off");
}
}
static class LightsControl {
public void turnOn() {
System.out.println("Lights are turned on");
}
public void turnOff() {
System.out.println("Lights are turned off");
}
}
static class HomeTheaterFacade {
private StereoSystem stereo;
private Projector projector;
private LightsControl lights;
public HomeTheaterFacade() {
stereo = new StereoSystem();
projector = new Projector();
lights = new LightsControl();
}
public void watchMovie() {
System.out.println("Getting ready to watch a movie...");
lights.turnOff();
projector.turnOn();
stereo.turnOn();
}
public void endMovie() {
System.out.println("Ending the movie...");
stereo.turnOff();
projector.turnOff();
lights.turnOn();
}
}
}
享元模式 Flyweight
package com.design.patternz;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class FlyweightPattern {
public static void main(String[] args) {
Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
for (int i = 0; i < 20; i++) {
Color randomColor = colors[(int) (Math.random() * colors.length)];
Shape circle = ShapeFactory.getCircle(randomColor);
circle.draw((int) (Math.random() * 100), (int) (Math.random() * 100));
}
}
interface Shape {
void draw(int x, int y);
}
static class Circle implements Shape {
private Color color;
public Circle(Color color) {
this.color = color;
}
@Override
public void draw(int x, int y) {
System.out.println("Drawing a " + color + " circle at (" + x + "," + y + ")");
}
}
static class ShapeFactory {
private static final Map<Color, Shape> circleMap = new HashMap<>();
public static Shape getCircle(Color color) {
Shape circle = circleMap.get(color);
if (circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
}
return circle;
}
}
}
代理模式 Proxy
package com.design.patternz;
public class ProxyPattern {
public static void main(String[] args) {
Image image = new ProxyImage("sample.jpg");
image.display();
image.display();
}
interface Image {
void display();
}
static class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadImageFromDisk();
}
private void loadImageFromDisk() {
System.out.println("Loading image from disk: " + filename);
}
public void display() {
System.out.println("Displaying image: " + filename);
}
}
static class ProxyImage implements Image {
private RealImage realImage;
private String filename;
public ProxyImage(String filename) {
this.filename = filename;
}
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
}
解释器模式 Interpreter
package com.design.patternz;
public class InterpreterPattern {
public static void main(String[] args) {
Expression expression = new AddExpression(
new NumberExpression(2),
new SubtractExpression(
new NumberExpression(3),
new NumberExpression(1)
)
);
int result = expression.interpret();
System.out.println("Result: " + result);
}
interface Expression {
int interpret();
}
static class NumberExpression implements Expression {
private int value;
public NumberExpression(int value) {
this.value = value;
}
@Override
public int interpret() {
return value;
}
}
static class AddExpression implements Expression {
private Expression leftOperand;
private Expression rightOperand;
public AddExpression(Expression leftOperand, Expression rightOperand) {
this.leftOperand = leftOperand;
this.rightOperand = rightOperand;
}
@Override
public int interpret() {
return leftOperand.interpret() + rightOperand.interpret();
}
}
static class SubtractExpression implements Expression {
private Expression leftOperand;
private Expression rightOperand;
public SubtractExpression(Expression leftOperand, Expression rightOperand) {
this.leftOperand = leftOperand;
this.rightOperand = rightOperand;
}
@Override
public int interpret() {
return leftOperand.interpret() - rightOperand.interpret();
}
}
}
模板方法模式 Template Method
package com.design.patternz;
public class TemplateMethodPattern {
public static void main(String[] args) {
AbstractClass template = new ConcreteClass();
template.templateMethod();
}
static abstract class AbstractClass {
public void templateMethod() {
step1();
step2();
step3();
}
abstract void step1();
abstract void step2();
abstract void step3();
}
static class ConcreteClass extends AbstractClass {
@Override
void step1() {
System.out.println("ConcreteClass: Step 1");
}
@Override
void step2() {
System.out.println("ConcreteClass: Step 2");
}
@Override
void step3() {
System.out.println("ConcreteClass: Step 3");
}
}
}
责任链模式 Chain of Responsibility
package com.design.patternz;
public class ChainOfResponsibilityPattern {
public static void main(String[] args) {
ReimbursementHandler manager = new ManagerHandler();
ReimbursementHandler departmentHead = new DepartmentHeadHandler();
ReimbursementHandler finance = new FinanceHandler();
manager.setSuccessor(departmentHead);
departmentHead.setSuccessor(finance);
ReimbursementRequest request1 = new ReimbursementRequest(800, "购买办公用品");
ReimbursementRequest request2 = new ReimbursementRequest(3000, "参加培训");
ReimbursementRequest request3 = new ReimbursementRequest(10000, "举办团建活动");
manager.handleRequest(request1);
manager.handleRequest(request2);
manager.handleRequest(request3);
}
static class ReimbursementRequest {
private double amount;
private String description;
public ReimbursementRequest(double amount, String description) {
this.amount = amount;
this.description = description;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
}
static abstract class ReimbursementHandler {
protected ReimbursementHandler successor;
public void setSuccessor(ReimbursementHandler successor) {
this.successor = successor;
}
public abstract void handleRequest(ReimbursementRequest request);
}
static class ManagerHandler extends ReimbursementHandler {
@Override
public void handleRequest(ReimbursementRequest request) {
if (request.getAmount() <= 1000) {
System.out.println("经理处理报销请求:" + request.getDescription());
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
static class DepartmentHeadHandler extends ReimbursementHandler {
@Override
public void handleRequest(ReimbursementRequest request) {
if (request.getAmount() <= 5000) {
System.out.println("部门主管处理报销请求:" + request.getDescription());
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
static class FinanceHandler extends ReimbursementHandler {
@Override
public void handleRequest(ReimbursementRequest request) {
System.out.println("财务部门处理报销请求:" + request.getDescription());
}
}
}
命令模式 Command
package com.design.patternz;
public class CommandPattern {
public static void main(String[] args) {
Light livingRoomLight = new Light();
LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight);
LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight);
RemoteControl remote = new RemoteControl();
remote.setCommand(livingRoomLightOn);
remote.pressButton();
remote.setCommand(livingRoomLightOff);
remote.pressButton();
}
interface Command {
void execute();
}
static class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
static class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}
static class Light {
void turnOn() {
System.out.println("Light is on");
}
void turnOff() {
System.out.println("Light is off");
}
}
static class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
}
迭代器模式 Iterator
package com.design.patternz;
import java.util.ArrayList;
import java.util.List;
public class IteratorPattern {
public static void main(String[] args) {
ConcreteCollection<String> collection = new ConcreteCollection<>();
collection.addItem("Item 1");
collection.addItem("Item 2");
collection.addItem("Item 3");
Iterator<String> iterator = collection.createIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
interface IterableCollection<T> {
Iterator<T> createIterator();
}
static class ConcreteCollection<T> implements IterableCollection<T> {
private List<T> items = new ArrayList<>();
public void addItem(T item) {
items.add(item);
}
@Override
public Iterator<T> createIterator() {
return new ConcreteIterator<>(items);
}
}
interface Iterator<T> {
boolean hasNext();
T next();
}
static class ConcreteIterator<T> implements Iterator<T> {
private List<T> items;
private int position = 0;
public ConcreteIterator(List<T> items) {
this.items = items;
}
@Override
public boolean hasNext() {
return position < items.size();
}
@Override
public T next() {
if (hasNext()) {
T item = items.get(position);
position++;
return item;
}
throw new IndexOutOfBoundsException("No more elements");
}
}
}
中介者模式 Mediator
package com.design.patternz;
import java.util.ArrayList;
import java.util.List;
public class MediatorPattern {
public static void main(String[] args) {
ConcreteChatMediator chatMediator = new ConcreteChatMediator();
User user1 = new User("Alice", chatMediator);
User user2 = new User("Bob", chatMediator);
User user3 = new User("Charlie", chatMediator);
chatMediator.addUser(user1);
chatMediator.addUser(user2);
chatMediator.addUser(user3);
user1.sendMessage("大家好!");
user2.sendMessage("你好,Alice!");
}
interface ChatMediator {
void sendMessage(String message, User user);
void addUser(User user);
}
static class ConcreteChatMediator implements ChatMediator {
private List<User> users = new ArrayList<>();
@Override
public void sendMessage(String message, User user) {
for (User u : users) {
if (u != user) {
u.receiveMessage(message);
}
}
}
@Override
public void addUser(User user) {
users.add(user);
}
}
static class User {
private String name;
private ChatMediator mediator;
public User(String name, ChatMediator mediator) {
this.name = name;
this.mediator = mediator;
}
public void sendMessage(String message) {
System.out.println(name + " 发送消息: " + message);
mediator.sendMessage(message, this);
}
public void receiveMessage(String message) {
System.out.println(name + " 收到消息: " + message);
}
}
}
备忘录模式 Memento
package com.design.patternz;
public class MementoPattern {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.setState("State 1");
System.out.println("Current State: " + originator.getState());
caretaker.setMemento(originator.createMemento());
originator.setState("State 2");
System.out.println("Updated State: " + originator.getState());
originator.restoreMemento(caretaker.getMemento());
System.out.println("Restored State: " + originator.getState());
}
static class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
static class Originator {
private String state;
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public Memento createMemento() {
return new Memento(state);
}
public void restoreMemento(Memento memento) {
state = memento.getState();
}
}
static class Caretaker {
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
}
观察者模式 Observer
package com.design.patternz;
import java.util.ArrayList;
import java.util.List;
public class ObserverPattern {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer observer1 = new ConcreteObserver("观察者1");
Observer observer2 = new ConcreteObserver("观察者2");
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.setState(10);
subject.setState(20);
subject.removeObserver(observer1);
subject.setState(30);
}
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
static class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyObservers();
}
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(state);
}
}
}
interface Observer {
void update(int state);
}
static class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(int state) {
System.out.println(name + " 收到更新,新状态为: " + state);
}
}
}
状态模式 State
package com.design.patternz;
public class StatePatternPattern {
public static void main(String[] args) {
Elevator elevator = new Elevator();
elevator.openDoors();
elevator.move();
elevator.closeDoors();
elevator.move();
elevator.stop();
elevator.openDoors();
}
interface ElevatorState {
void openDoors();
void closeDoors();
void move();
void stop();
}
static class OpenState implements ElevatorState {
@Override
public void openDoors() {
System.out.println("Doors are already open.");
}
@Override
public void closeDoors() {
System.out.println("Closing doors.");
}
@Override
public void move() {
System.out.println("Cannot move while doors are open.");
}
@Override
public void stop() {
System.out.println("Stopping while doors are open.");
}
}
static class CloseState implements ElevatorState {
@Override
public void openDoors() {
System.out.println("Opening doors.");
}
@Override
public void closeDoors() {
System.out.println("Doors are already closed.");
}
@Override
public void move() {
System.out.println("Moving.");
}
@Override
public void stop() {
System.out.println("Stopping.");
}
}
static class Elevator {
private ElevatorState state;
public Elevator() {
state = new CloseState();
}
public void setState(ElevatorState state) {
this.state = state;
}
public void openDoors() {
state.openDoors();
}
public void closeDoors() {
state.closeDoors();
}
public void move() {
state.move();
}
public void stop() {
state.stop();
}
}
}
策略模式 Strategy
package com.design.patternz;
public class StrategyPattern {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setOperation(new Addition());
int result1 = calculator.performOperation(5, 3);
System.out.println("Addition Result: " + result1);
calculator.setOperation(new Subtraction());
int result2 = calculator.performOperation(10, 4);
System.out.println("Subtraction Result: " + result2);
calculator.setOperation(new Multiplication());
int result3 = calculator.performOperation(6, 2);
System.out.println("Multiplication Result: " + result3);
}
interface MathOperation {
int operate(int a, int b);
}
static class Addition implements MathOperation {
@Override
public int operate(int a, int b) {
return a + b;
}
}
static class Subtraction implements MathOperation {
@Override
public int operate(int a, int b) {
return a - b;
}
}
static class Multiplication implements MathOperation {
@Override
public int operate(int a, int b) {
return a * b;
}
}
static class Calculator {
private MathOperation operation;
public void setOperation(MathOperation operation) {
this.operation = operation;
}
public int performOperation(int a, int b) {
if (operation != null) {
return operation.operate(a, b);
}
throw new IllegalStateException("No operation set");
}
}
}
访问者模式 Visitor
package com.design.patternz;
public class VisitorPattern {
public static void main(String[] args) {
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
AreaCalculator areaCalculator = new AreaCalculator();
circle.accept(areaCalculator);
System.out.println("Total area: " + areaCalculator.getArea());
rectangle.accept(areaCalculator);
System.out.println("Total area: " + areaCalculator.getArea());
}
interface Shape {
void accept(ShapeVisitor visitor);
}
static class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
@Override
public void accept(ShapeVisitor visitor) {
visitor.visit(this);
}
}
static class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
@Override
public void accept(ShapeVisitor visitor) {
visitor.visit(this);
}
}
interface ShapeVisitor {
void visit(Circle circle);
void visit(Rectangle rectangle);
}
static class AreaCalculator implements ShapeVisitor {
private double area;
@Override
public void visit(Circle circle) {
area += Math.PI * circle.getRadius() * circle.getRadius();
}
@Override
public void visit(Rectangle rectangle) {
area += rectangle.getWidth() * rectangle.getHeight();
}
public double getArea() {
return area;
}
}
}