单例模式
bean的形式
java
@Bean
public TestService testService(){
return new TestServiceImpl();
}
枚举类形式
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public enum SingletonThreadPool {
INSTANCE;
private ExecutorService threadPool;
SingletonThreadPool() {
// 创建一个固定大小的线程池
threadPool = Executors.newFixedThreadPool(5);
}
public void executeTask(Runnable task) {
threadPool.execute(task);
}
//使用案例
public static void main(String[] args) {
// 提交任务到线程池
SingletonThreadPool.INSTANCE.executeTask(() -> {
System.out.println("任务正在执行...");
});
}
}
工厂模式
简单工厂
java
public class SimplePizzaFactory {
public Pizza CreatePizza(String ordertype) {
Pizza pizza = null;
if (ordertype.equals("cheese")) {
pizza = new CheesePizza();
} else if (ordertype.equals("greek")) {
pizza = new GreekPizza();
} else if (ordertype.equals("pepper")) {
pizza = new PepperPizza();
}
return pizza;
}
}
抽象工厂
java
public interface AbsFactory {
//创建pizza
Pizza CreatePizza(String ordertype);
//创建Cake
Cake CreateCake(String ordertype);
}
public class LDFactory implements AbsFactory {
@Override
public Pizza CreatePizza(String ordertype) {
Pizza pizza = null;
if ("cheese".equals(ordertype)) {
pizza = new LDCheesePizza();
} else if ("pepper".equals(ordertype)) {
pizza = new LDPepperPizza();
}
return pizza;
}
@Override
public Cake CreateCake(String ordertype) {
Cake cake= null;
if ("cheese".equals(ordertype)) {
cake = new LDCheeseCake();
} else if ("pepper".equals(ordertype)) {
cake = new LDPepperCake();
}
return cake;
}
}
建造者模式
工具类
java
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
@Slf4j
public class BuilderUtil<T> {
/**
* 创建对象的构造方法
*/
private Supplier<T> createInstance;
/**
* 设值的函数方法集合
*/
private List<Consumer<T>> consumers;
private BuilderUtil() {
}
/**
* 创建builder实例
*
* @param constructor build对象的构造方法
* @param <T> build对象的类型
* @return builder实例
*/
public static <T> BuilderUtil<T> create(Supplier<T> constructor) {
BuilderUtil<T> instance = new BuilderUtil<>();
instance.createInstance = constructor;
instance.consumers = new ArrayList<>(8);
return instance;
}
/**
* 设置对象属性
*
* @param consumer 对象属性设值方法
* @param p 参数
* @param <P> 参数泛型
* @return 当前builder实例
*/
public <P> BuilderUtil<T> with(BiConsumer<T, P> consumer, P p) {
consumers.add(instance -> consumer.accept(instance, p));
return this;
}
/**
* 生成对象
*
* @return 对象实例
*/
public T build() {
T t = createInstance.get();
for (Consumer<T> consumer : consumers) {
consumer.accept(t);
}
return t;
}
}
使用
java
Test user = BuilderUtil.create(Test::new)
.with(Test::setName, "John")
.with(Test::setItem1, "Doe")
.build();
策略模式
抽象类
java
//父类
public abstract class CustomService {
public abstract Boolean isDoSharing();
}
//子类
@Service("b_test")
public class TestService extends CustomService {
@Override
public Boolean isDoSharing() {
return null;
}
}
//使用
@Autowired
private Map<String, CustomService> customServiceMap;
public void test() {
Boolean bTest = customServiceMap.get("b_test").isDoSharing();
}
接口
java
//接口
public interface CustomService {
Boolean isDoSharing();
}
//实现
@Service("b_test")
public class TestService implements CustomService {
@Override
public Boolean isDoSharing() {
return null;
}
}
//使用
@Autowired
private Map<String, CustomService> customServiceMap;
public void test() {
Boolean bTest = customServiceMap.get("b_test").isDoSharing();
}
模板方法模式
java
//模板类
public abstract class CustomService {
/***
* 创建模板
* @return 结果
*/
public String make() {
doSharing();
createMysqlTable();
batchInsertMysql();
return "调用成功!";
}
public abstract void doSharing();
public abstract void createMysqlTable();
public abstract void batchInsertMysql();
}
//实现类
@Service("b_test")
public class TestService extends CustomService {
@Override
public void doSharing() {
}
@Override
public void createMysqlTable() {
}
@Override
public void batchInsertMysql() {
}
}
//使用
public void test() {
TestService testService = new TestService();
String make = testService.make();
}
观察者模式
java
import java.util.ArrayList;
import java.util.List;
// 主题接口
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// 观察者接口
interface Observer {
void update(String message);
}
// 具体主题实现
class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update("Subject's state has changed");
}
}
// 主题状态改变时调用该方法
public void stateChanged() {
notifyObservers();
}
}
// 具体观察者实现
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);
}
}
// 测试类
public class ObserverPatternExample {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
ConcreteObserver observer1 = new ConcreteObserver("Observer 1");
ConcreteObserver observer2 = new ConcreteObserver("Observer 2");
subject.registerObserver(observer1);
subject.registerObserver(observer2);
subject.stateChanged();
}
}
责任链模式
java
// 定义处理请求的接口
interface Handler {
void handleRequest(int request);
void setNextHandler(Handler nextHandler);
}
// 具体处理请求的类
class ConcreteHandler implements Handler {
private Handler nextHandler;
@Override
public void handleRequest(int request) {
if (request >= 0 && request < 10) {
System.out.println("ConcreteHandler 处理请求:" + request);
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
@Override
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Handler handler1 = new ConcreteHandler();
Handler handler2 = new ConcreteHandler();
handler1.setNextHandler(handler2);
handler1.handleRequest(5);
handler1.handleRequest(15);
}
}
代理模式
java
import java.lang.reflect.Proxy;
public class ProxyUtil {
public static <T> T createProxy(Class<T> interfaceClass, T target) {
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
new Class[]{interfaceClass},
(proxy, method, args) -> {
System.out.println("动态代理执行前操作");
Object result = method.invoke(target, args);
System.out.println("动态代理执行后操作");
return result;
});
}
public static void main(String[] args) {
Subject realSubject = new RealSubject();
Subject proxy = ProxyUtil.createProxy(Subject.class, realSubject);
proxy.doSomething();
}
}