优秀代码都遵循的六大原则
Java六大设计原则(SOLID +1)是面向对象设计的核心准则:
单一职责原则 (SRP)
- 一个类只负责一个功能领域
- 示例:用户管理类不应同时处理登录和支付逻辑
开闭原则 (OCP)
- 对扩展开放,对修改关闭
- 通过抽象层(接口/抽象类)实现功能扩展
里氏替换原则 (LSP)
- 子类必须能替换父类且不影响程序正确性
- 典型违反:子类重写父类方法抛出更宽泛异常
接口隔离原则 (ISP)
- 客户端不应依赖不需要的接口方法
- 解决方案:将大接口拆分为多个小接口
依赖倒置原则 (DIP)
- 高层模块不应依赖低层模块,二者都应依赖抽象
- 通过依赖注入实现(如Spring IoC)
迪米特法则 (LoD)
- 最少知识原则,对象只与直接朋友通信
- 避免链式调用:
a.getB().getC().doSomething()扩展原则:组合优于继承(非SOLID但重要)
- 优先使用对象组合而非类继承实现代码复用
- 示例:策略模式通过组合不同算法对象实现行为变化
这些原则共同作用可提升代码的可维护性、扩展性和复用性,是设计模式的理论基础。实际开发中需根据场景灵活运用而非教条执行。
责任链
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class AuditManagementFilterChain implements InitializingBean, ApplicationContextAware {
private IAuditManagementFilter[] filters = new IAuditManagementFilter[0];
private int pos = 0;
private int n = 0;
private ApplicationContext appContext;
private void addFilter(IAuditManagementFilter newFilter) {
IAuditManagementFilter[] newFilters = this.filters;
for (IAuditManagementFilter filter : newFilters) {
if (filter == newFilter) {
return;
}
}
if (this.n == this.filters.length) {
newFilters = new IAuditManagementFilter[this.n + 10];
System.arraycopy(this.filters, 0, newFilters, 0, this.n);
this.filters = newFilters;
}
this.filters[this.n++] = newFilter;
}
public void doFilter(Object obj) {
if (this.pos < this.n) {
IAuditManagementFilter filter = this.filters[this.pos++];
filter.doFilter(obj, this);
}
}
@Override
public void afterPropertiesSet() throws Exception {
this.appContext
.getBeansOfType(IAuditManagementFilter.class)
.values()
.forEach(this::addFilter);
}
@Override
public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
this.appContext = applicationContext;
}
}
工厂
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class BankPayNotifyFactory implements InitializingBean, ApplicationContextAware {
private static final Map<String, BankPayNotifyStrategy> NOTIFY_MAP = new HashMap<>(8);
private ApplicationContext appContext;
/**
* 根据银行编码获取对应的处理器
*
* @param bankChannelCode 银行渠道编码
* @return
*/
public BankPayNotifyStrategy getHandler(String bankChannelCode) {
return NOTIFY_MAP.get(bankChannelCode);
}
@Override
public void afterPropertiesSet() throws Exception {
this.appContext.getBeansOfType(BankPayNotifyStrategy.class)
.values()
.forEach(handler -> NOTIFY_MAP.put(handler.getBankChannelCode(), handler));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.appContext = applicationContext;
}
}
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class TagHandlerStrategyFactory {
private static final Map<String, TagHandlerStrategy> strategyMap = new HashMap<>();
public static TagHandlerStrategy addStrategy(TagHandlerStrategy strategy) {
log.info("Register a policy class[{}]", strategy.getClass().getName());
return strategyMap.put(strategy.getClass().getSimpleName(), strategy);
}
public static TagHandlerStrategy getStrategy(String name) {
return strategyMap.get(name);
}
}
门面
// 子系统
class CPU { void start() { /* ... */ } }
class Memory { void load() { /* ... */ } }
// 外观类
class ComputerFacade {
private CPU cpu;
private Memory memory;
public void startComputer() {
cpu.start();
memory.load();
}
}
// 客户端调用
facade.startComputer(); // 隐藏了CPU和Memory的细节
// 子系统:DVD播放器
class DvdPlayer {
public void on() { System.out.println("DVD启动"); }
public void play(String movie) { System.out.println("播放电影:" + movie); }
}
// 子系统:投影仪
class Projector {
public void on() { System.out.println("投影仪开启"); }
}
// 外观类
class HomeTheaterFacade {
private DvdPlayer dvd;
private Projector projector;
public HomeTheaterFacade() {
this.dvd = new DvdPlayer();
this.projector = new Projector();
}
public void watchMovie(String movie) {
projector.on();
dvd.on();
dvd.play(movie);
}
}
// 客户端调用
public class Client {
public static void main(String[] args) {
HomeTheaterFacade facade = new HomeTheaterFacade();
facade.watchMovie("星际穿越");
}
}
适配器
// 目标接口(客户端期望的接口)
interface MediaPlayer {
void play(String audioType, String fileName);
}
// 被适配者:现有实现类(不兼容接口)
class AdvancedMediaPlayer {
public void playMp4(String fileName) {
System.out.println("Playing MP4 file: " + fileName);
}
public void playVlc(String fileName) {
System.out.println("Playing VLC file: " + fileName);
}
}
// 适配器类(实现目标接口并封装被适配者)
class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedPlayer;
public MediaAdapter(String audioType) {
if(audioType.equalsIgnoreCase("vlc")) {
advancedPlayer = new AdvancedMediaPlayer();
} else if(audioType.equalsIgnoreCase("mp4")) {
advancedPlayer = new AdvancedMediaPlayer();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")) {
advancedPlayer.playVlc(fileName);
} else if(audioType.equalsIgnoreCase("mp4")) {
advancedPlayer.playMp4(fileName);
}
}
}
// 客户端代码
public class AdapterDemo {
public static void main(String[] args) {
MediaPlayer player = new MediaAdapter("mp4");
player.play("mp4", "movie.mp4");
player = new MediaAdapter("vlc");
player.play("vlc", "song.vlc");
}
}
事件
@Component
public class BankWithholdRecordEventUtil {
@Autowired
private ApplicationEventPublisher publisher;
/**
* 发布监听
*
* @param bankWithholdRecord
*/
public void publishBankWithholdRecordEvent(BankWithholdRecord bankWithholdRecord) {
publisher.publishEvent(new BankWithholdRecordEvent(bankWithholdRecord));
}
}
public class BankWithholdRecordEvent extends ApplicationEvent {
/**
* 事件
*
* @param source
*/
public BankWithholdRecordEvent(BankWithholdRecord source) {
super(source);
}
}
@Component
@Slf4j
public class BankWithholdRecordListener {
@Autowired
private IBankWithholdRecordService bankWithholdRecordService;
/**
* 代扣流水监听
*
* @param event
*/
@Async
@EventListener({BankWithholdRecordEvent.class})
public void saveWithholdRecord(BankWithholdRecordEvent event) {
BankWithholdRecord bankWithholdRecord = (BankWithholdRecord) event.getSource();
log.info("进入代扣流水监听方法:{}", bankWithholdRecord);
bankWithholdRecordService.insertBankWithholdRecord(bankWithholdRecord);
}
}
监听
import java.util.*;
public class Button {
private List<ClickListener> listeners = new ArrayList<>();
public void addListener(ClickListener listener) {
listeners.add(listener);
}
public void click() {
listeners.forEach(ClickListener::onClick);
}
}
public interface ClickListener {
void onClick();
}
public class Main {
public static void main(String[] args) {
Button button = new Button();
button.addListener(() -> System.out.println("Button clicked!"));
button.click();
}
}
发布订阅
import java.util.*;
public class EventBroker {
private Map<String, List<Subscriber>> topics = new HashMap<>();
public void subscribe(String topic, Subscriber subscriber) {
topics.computeIfAbsent(topic, k -> new ArrayList<>()).add(subscriber);
}
public void publish(String topic, String message) {
topics.getOrDefault(topic, Collections.emptyList())
.forEach(sub -> sub.onEvent(message));
}
}
public interface Subscriber {
void onEvent(String message);
}
public class Main {
public static void main(String[] args) {
EventBroker broker = new EventBroker();
broker.subscribe("news", message -> System.out.println("Sub1 received: " + message));
broker.publish("news", "Java 21 released!");
}
}
单例
最好的单例就是枚举!!!
public class Singleton {
// 方式1:双重检查锁定(适用于JDK5+)
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;
}
// 方式2:枚举单例(推荐写法)
public enum EnumSingleton {
INSTANCE;
public void doSomething() {
System.out.println("Enum singleton working");
}
}
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true
EnumSingleton.INSTANCE.doSomething();
}
}
1万+

被折叠的 条评论
为什么被折叠?



