上海网站备案核验单状态查询,浏阳商务局网站溪江农贸市场建设,山西运城给网站做系统的公司,网站建设工作要求一、创建型模式
1. 单例模式
定义
确保一个类只有一个实例#xff0c;并提供一个全局访问点。
实现方式 饿汉式#xff08;线程安全#xff0c;但可能浪费资源#xff09; public class Singleton {// 静态变量#xff0c;类加载时初始化private static final Singlet…一、创建型模式
1. 单例模式
定义
确保一个类只有一个实例并提供一个全局访问点。
实现方式 饿汉式线程安全但可能浪费资源 public class Singleton {// 静态变量类加载时初始化private static final Singleton instance new Singleton();// 私有构造方法防止外部实例化private Singleton() {}// 提供全局访问点public static Singleton getInstance() {return instance;}// 示例方法public void showMessage() {System.out.println(Hello from Singleton!);}
}// 测试类
public class TestSingleton {public static void main(String[] args) {Singleton singleton Singleton.getInstance();singleton.showMessage();}
}懒汉式延迟加载需考虑线程安全 public class Singleton {private static volatile Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance null) {synchronized (Singleton.class) {if (instance null) {instance new Singleton();}}}return instance;}public void showMessage() {System.out.println(Hello from Lazy Singleton!);}
}// 测试类
public class TestSingleton {public static void main(String[] args) {Singleton singleton Singleton.getInstance();singleton.showMessage();}
}应用场景
数据库连接池。全局配置管理器。 2. 工厂模式
分类 简单工厂模式 将对象的创建集中在一个工厂类中。 public interface Shape {void draw();
}public class Circle implements Shape {Overridepublic void draw() {System.out.println(Drawing a circle);}
}public class Rectangle implements Shape {Overridepublic void draw() {System.out.println(Drawing a rectangle);}
}public class ShapeFactory {public static Shape getShape(String type) {if (circle.equalsIgnoreCase(type)) {return new Circle();} else if (rectangle.equalsIgnoreCase(type)) {return new Rectangle();}return null;}
}// 测试类
public class TestFactory {public static void main(String[] args) {Shape shape1 ShapeFactory.getShape(circle);shape1.draw();Shape shape2 ShapeFactory.getShape(rectangle);shape2.draw();}
}工厂方法模式 定义一个创建对象的接口由子类决定实例化哪个类。 public interface Shape {void draw();
}public class Circle implements Shape {Overridepublic void draw() {System.out.println(Drawing a circle);}
}public abstract class ShapeFactory {public abstract Shape createShape();
}public class CircleFactory extends ShapeFactory {Overridepublic Shape createShape() {return new Circle();}
}// 测试类
public class TestFactoryMethod {public static void main(String[] args) {ShapeFactory factory new CircleFactory();Shape shape factory.createShape();shape.draw();}
}抽象工厂模式 提供一个创建一系列相关或依赖对象的接口。 public interface Button {void render();
}public interface Checkbox {void render();
}public class WindowsButton implements Button {Overridepublic void render() {System.out.println(Rendering a Windows button);}
}public class WindowsCheckbox implements Checkbox {Overridepublic void render() {System.out.println(Rendering a Windows checkbox);}
}public interface GUIFactory {Button createButton();Checkbox createCheckbox();
}public class WindowsFactory implements GUIFactory {Overridepublic Button createButton() {return new WindowsButton();}Overridepublic Checkbox createCheckbox() {return new WindowsCheckbox();}
}// 测试类
public class TestAbstractFactory {public static void main(String[] args) {GUIFactory factory new WindowsFactory();Button button factory.createButton();button.render();Checkbox checkbox factory.createCheckbox();checkbox.render();}
}应用场景
动态创建对象如 UI 组件、数据库驱动。 3. 建造者模式
定义
将复杂对象的构建与其表示分离使得同样的构建过程可以创建不同的表示。
实现方式
public class Computer {private String cpu;private String ram;private String storage;private Computer(Builder builder) {this.cpu builder.cpu;this.ram builder.ram;this.storage builder.storage;}public static class Builder {private String cpu;private String ram;private String storage;public Builder setCpu(String cpu) {this.cpu cpu;return this;}public Builder setRam(String ram) {this.ram ram;return this;}public Builder setStorage(String storage) {this.storage storage;return this;}public Computer build() {return new Computer(this);}}Overridepublic String toString() {return Computer{ cpu cpu \ , ram ram \ , storage storage \ };}
}// 测试类
public class TestBuilder {public static void main(String[] args) {Computer computer new Computer.Builder().setCpu(Intel i7).setRam(16GB).setStorage(512GB SSD).build();System.out.println(computer);}
}应用场景
构建复杂的对象如 HTML 文档生成器、游戏角色创建器。 4. 原型模式
定义
通过复制现有对象来创建新对象而不是通过 new 创建。
实现方式
import java.util.Objects;public class Prototype implements Cloneable {private String data;public Prototype(String data) {this.data data;}public String getData() {return data;}public void setData(String data) {this.data data;}Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}Overridepublic String toString() {return Prototype{ data data \ };}
}// 测试类
public class TestPrototype {public static void main(String[] args) throws CloneNotSupportedException {Prototype prototype new Prototype(Original Data);Prototype clonedPrototype (Prototype) prototype.clone();System.out.println(Original: prototype);System.out.println(Cloned: clonedPrototype);clonedPrototype.setData(Modified Data);System.out.println(After Modification:);System.out.println(Original: prototype);System.out.println(Cloned: clonedPrototype);}
}应用场景
需要频繁创建相似对象时如游戏中的敌人克隆。 二、结构型模式
1. 适配器模式
定义
将一个类的接口转换成客户希望的另一个接口使原本不兼容的类可以一起工作。
实现方式 类适配器通过继承实现 public interface Target {void request();
}public class Adaptee {public void specificRequest() {System.out.println(Specific Request);}
}public class Adapter extends Adaptee implements Target {Overridepublic void request() {specificRequest();}
}// 测试类
public class TestAdapter {public static void main(String[] args) {Target target new Adapter();target.request();}
}对象适配器通过组合实现 public class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee adaptee;}Overridepublic void request() {adaptee.specificRequest();}
}// 测试类
public class TestAdapter {public static void main(String[] args) {Adaptee adaptee new Adaptee();Target target new Adapter(adaptee);target.request();}
}应用场景
第三方库与现有系统的集成。 2. 装饰者模式
定义
动态地为对象添加新的功能而无需修改其原始代码。
实现方式
public interface Component {void operation();
}public class ConcreteComponent implements Component {Overridepublic void operation() {System.out.println(Performing base operation);}
}public abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component component;}Overridepublic void operation() {component.operation();}
}public class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) {super(component);}Overridepublic void operation() {super.operation();addedBehavior();}private void addedBehavior() {System.out.println(Adding behavior A);}
}// 测试类
public class TestDecorator {public static void main(String[] args) {Component component new ConcreteComponent();Component decoratedComponent new ConcreteDecoratorA(component);decoratedComponent.operation();}
}应用场景
动态扩展功能如 Java I/O 流中的 BufferedReader 和 FileReader。 3. 代理模式
定义
为某个对象提供一个代理以控制对该对象的访问。
实现方式
public interface Service {void doSomething();
}public class RealService implements Service {Overridepublic void doSomething() {System.out.println(Executing real service);}
}public class ProxyService implements Service {private RealService realService;Overridepublic void doSomething() {if (realService null) {realService new RealService();}System.out.println(Proxy: Before calling real service);realService.doSomething();System.out.println(Proxy: After calling real service);}
}// 测试类
public class TestProxy {public static void main(String[] args) {Service proxy new ProxyService();proxy.doSomething();}
}应用场景
远程代理如 RMI。虚拟代理如图片懒加载。 4. 桥接模式
定义
将抽象部分与实现部分分离使它们都可以独立变化。
实现方式
public interface Implementor {void operationImpl();
}public class ConcreteImplementorA implements Implementor {Overridepublic void operationImpl() {System.out.println(Concrete Implementor A);}
}public abstract class Abstraction {protected Implementor implementor;public Abstraction(Implementor implementor) {this.implementor implementor;}public abstract void operation();
}public class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor implementor) {super(implementor);}Overridepublic void operation() {implementor.operationImpl();}
}// 测试类
public class TestBridge {public static void main(String[] args) {Implementor implementor new ConcreteImplementorA();Abstraction abstraction new RefinedAbstraction(implementor);abstraction.operation();}
}应用场景
多维度扩展如不同形状和颜色的组合。 三、行为型模式
1. 观察者模式
定义
定义了一种一对多的依赖关系当一个对象的状态发生改变时所有依赖于它的对象都会收到通知并自动更新。
实现方式
import java.util.ArrayList;
import java.util.List;public interface Observer {void update(String message);
}public class ConcreteObserver implements Observer {private String name;public ConcreteObserver(String name) {this.name name;}Overridepublic void update(String message) {System.out.println(name received: message);}
}public class Subject {private ListObserver observers new ArrayList();public void addObserver(Observer observer) {observers.add(observer);}public void notifyObservers(String message) {for (Observer observer : observers) {observer.update(message);}}
}// 测试类
public class TestObserver {public static void main(String[] args) {Subject subject new Subject();Observer observer1 new ConcreteObserver(Observer 1);Observer observer2 new ConcreteObserver(Observer 2);subject.addObserver(observer1);subject.addObserver(observer2);subject.notifyObservers(New Message);}
}应用场景
订阅/发布系统如消息队列、事件监听器。 2. 生产者/消费者模式
定义
通过共享缓冲区实现生产者和消费者的解耦。
实现方式
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;public class ProducerConsumer {private QueueInteger buffer new LinkedList();private int capacity 5;public synchronized void produce() throws InterruptedException {while (buffer.size() capacity) {wait();}int value new Random().nextInt(100);buffer.add(value);System.out.println(Produced: value);notifyAll();}public synchronized void consume() throws InterruptedException {while (buffer.isEmpty()) {wait();}int value buffer.poll();System.out.println(Consumed: value);notifyAll();}
}// 测试类
public class TestProducerConsumer {public static void main(String[] args) {ProducerConsumer pc new ProducerConsumer();Thread producerThread new Thread(() - {try {while (true) {pc.produce();Thread.sleep(1000);}} catch (InterruptedException e) {e.printStackTrace();}});Thread consumerThread new Thread(() - {try {while (true) {pc.consume();Thread.sleep(1000);}} catch (InterruptedException e) {e.printStackTrace();}});producerThread.start();consumerThread.start();}
}应用场景
消息队列。多线程任务调度。 3. 策略模式
定义
定义了一系列算法并将每个算法封装起来使它们可以互换。
实现方式
public interface Strategy {void execute();
}public class StrategyA implements Strategy {Overridepublic void execute() {System.out.println(Executing Strategy A);}
}public class StrategyB implements Strategy {Overridepublic void execute() {System.out.println(Executing Strategy B);}
}public class Context {private Strategy strategy;public void setStrategy(Strategy strategy) {this.strategy strategy;}public void executeStrategy() {strategy.execute();}
}// 测试类
public class TestStrategy {public static void main(String[] args) {Context context new Context();context.setStrategy(new StrategyA());context.executeStrategy();context.setStrategy(new StrategyB());context.executeStrategy();}
}应用场景
支付方式选择如支付宝、微信支付。 4. 模板方法模式
定义
定义一个操作中的算法骨架而将一些步骤延迟到子类中。
实现方式
public abstract class Game {public final void play() {initialize();startPlay();endPlay();}protected abstract void initialize();protected abstract void startPlay();protected abstract void endPlay();
}public class Football extends Game {Overrideprotected void initialize() {System.out.println(Football Game Initialized!);}Overrideprotected void startPlay() {System.out.println(Football Game Started!);}Overrideprotected void endPlay() {System.out.println(Football Game Finished!);}
}// 测试类
public class TestTemplateMethod {public static void main(String[] args) {Game game new Football();game.play();}
}应用场景
固定流程的业务逻辑如游戏开发、报表生成。 5. 状态模式
定义
允许对象在其内部状态改变时改变其行为。
实现方式
public interface State {void handle();
}public class ConcreteStateA implements State {Overridepublic void handle() {System.out.println(Handling state A);}
}public class ConcreteStateB implements State {Overridepublic void handle() {System.out.println(Handling state B);}
}public class Context {private State state;public void setState(State state) {this.state state;}public void request() {state.handle();}
}// 测试类
public class TestState {public static void main(String[] args) {Context context new Context();context.setState(new ConcreteStateA());context.request();context.setState(new ConcreteStateB());context.request();}
}应用场景
不同状态下执行不同逻辑如订单状态管理。