设计模式六大原则
- 单一职责原则
- 开闭原则
- 里氏替换原则
- 依赖倒置原则
- 接口隔离原则
- 迪米特法则
代码的坏味道
Long Method(过长方法)
public void reserve(Integer orderId){
//此处省略1000行代码
//行复杂度1000,分支复杂度100
}
方案:拆分成独立的子方法
//level 1
public boolean reserve(Integer orderId){
ReserveContext context = fetchData(orderId);
if(!precheckInventory(context)){
insufficientInventory(context);
return false;
}
if(reserveEntirely(context)){
return true;
}
insufficientInventory(context);
return false;
}
//level 2
private ReserveContext fetchData(Integer orderId){
//此处有100行
}
//level 2
private boolean precheckInventory(ReserveContext context){
//此处有100行
}
//level 2
private boolean insufficientInventory(ReserveContext context){
//其他代码100行
addInventoryDemand();
notifyLackGoodsCancel();
}
//level 2
private boolean reserveEntirely(ReserveContext context){
//其他代码100行
deductInventory();
updateOrder();
notifyPick();
notifyAutoDeliver();
}
//level 3
private boolean addInventoryDemand(){
//此处有100行
}
//level 3
private boolean deductInventory(){
//此处有100行
}
//level 3
private boolean updateOrder(){
//此处有20行
}
//level 3
private boolean notifyPick(){
//此处有30行
}
//level 3
private boolean notifyAutoDeliver(){
//此处有125行
}
//level 3
private boolean notifyLackGoodsCancel(){
//此处有50行
}
Large Class(过大类)
方案:把不同的业务拆分到独立的类中
class InventoryServiceImpl implements InventoryService {
//level 3
private boolean addInventoryDemand(){
//此处有100行
}
//level 3
private boolean deductInventory(){
//此处有100行
}
}
interface ReserveListener{
void onInventoryInsufficient(ReserveContext context);
void onReserveSuccess(ReserveContext context);
}
abstract class EmptyReserveListener implements ReserveListener {
void onInventoryInsufficient(ReserveContext context){};
void onReserveSuccess(ReserveContext context){};
}
class UpdateOrderListener extends EmptyReserveListener {
void onReserveSuccess(ReserveContext context){
//此处有20行
}
}
class NotifyPickListener extends EmptyReserveListener {
void onReserveSuccess(ReserveContext context){
//此处有30行
}
}
class NotifyAutoDeliverListener extends EmptyReserveListener {
void onReserveSuccess(ReserveContext context){
//此处有125行
}
}
class NotifyLackGoodsCancelListener extends EmptyReserveListener {
void onInventoryInsufficient(ReserveContext context){
//此处有125行
}
}
class CompositeReserveListener implements ReserveListener {
private List<ReserveListener> listeners = new ArrayList<>();
void onInventoryInsufficient(ReserveContext context){
for(ReserveListener each : listeners){
each.onInventoryInsufficient(context);
}
}
void onReserveSuccess(ReserveContext context){
for(ReserveListener each : listeners){
each.onReserveSuccess(context);
}
}
}
class ReserveService {
private InventoryService inventoryService;
//level 2
private boolean insufficientInventory(ReserveContext context){
//其他代码100行
addInventoryDemand();
notifyLackGoodsCancel();
}
//level 2
private boolean reserveEntirely(ReserveContext context){
//其他代码100行
deductInventory();
updateOrder();
notifyPick();
notifyAutoDeliver();
}
}
Duplicated Code(重复的代码)
方案:抽取到公共的类,模版方法
Redis redis = initRedis();
Integer randomValue = Random.randomInt();
redis.set("key", randomValue, NX,PX,1000)
try{
//do something in lock
//此处省略200行...
}finally{
redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end", "key", randomValue)
}
abstract class RedisLockTemplate {
void doWithLock(){
Redis redis = initRedis();
Integer randomValue = Random.randomInt();
redis.set("key", randomValue, NX,PX,1000)
try{
doWithInLock();
}finally{
redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end", "key", randomValue)
}
}
abstract void doWithInLock();
}
class OrderServcieImpl extends RedisLockTemplate {
void doWIthInLock(){
//此处省略200行
}
}
interface Callback{
void doWithInLock();
}
class RedisLockTemplate {
void doWithLock(RedisCallBack callBack){
Redis redis = initRedis();
Integer randomValue = Random.randomInt();
redis.set("key", randomValue, NX,PX,1000)
try{
callBack.doWithInLock();
}finally{
redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end", "key", randomValue)
}
}
class OrderServcieImpl {
private RedisLockTemplate lock = new RedisLockTemplate();
public void syncOrder(Order order){
lock.doWithLock(() -> {
...
//此处省略200行
});
}
}
方案:定义接口,生命周期
interface Servlet {
void init();
void service(ServletRequest req, ServletResponse res)
void destroy();
}
class container {
void void service(ServletRequest req, ServletResponse res) {
Servlet servlet = getServlet();
servlet.init();
servlet.service(req, res);
servlet.destroy();
}
}
Long Parameter List(过长參数列表)
//出库
void stockOut(String shipmentId, String trackingNumber, String boxCode, Boolean basketFlag, String fromFacilityId, String userName, String packager);
方案:提取参数对象,Builder模式
Class StockRequest {
String shipmentId;
String trackingNumber;
String boxCode;
Boolean basketFlag;
String fromFacilityId;
String userName;
String packager;
//getter
//setter
}
void stockOut(StockRequest stockRequest);
Switch Statements(过多的分支)
if(partyId = 65588){
...
...
...
...
...
//此处省略100行
} else if(partyId = 65530){
...
...
...
...
...
//此处省略100行
} else if(partyId = 65540){
...
...
...
...
...
//此处省略100行
} else if(partyId = 65539){
...
...
...
...
...
//此处省略100行
} else if(partyId = 65542){
...
...
...
...
...
//此处省略100行
}
方案:提取接口,策略模式
interface PartyProcessor {
void processParty()
}
class FDProcessor implements PartyProcessor {
void processParty(){
...
//此处省略100行
}
}
class AZProcessor implements PartyProcessor {
void processParty(){
...
//此处省略100行
}
}
Map<Integer, PartyProcessor> processorByPartyId = ...;
processorByPartyId.get(partyId).processParty();
if(condition1){
...
...
...
...
...
//此处省略100行
} else if(condition2){
...
...
...
...
...
//此处省略100行
} else if(condition3){
...
...
...
...
...
//此处省略100行
} else if(condition4){
...
...
...
...
...
//此处省略100行
} else if(condition5){
...
...
...
...
...
//此处省略100行
}
interface Strategy {
boolean applyable(condition);
void process()
}
class Strategy1 implements Strategy {
boolean applyable(condition){
return condition == condition1;
}
void process(){
...
//此处省略100行
}
}
class Strategy2 implements Strategy {
boolean applyable(condition){
return condition == condition2;
}
void process(){
...
//此处省略100行
}
}
List<Strategy> strategies = ...;
for(Strategy each : strategies){
if(each.applyable(condition)){
each.process();
}
}
Feature Envy(依恋情结)
class InventoryController {
public void inventoryLoss(String dispatchSn, String user){
//page controller logic 100行
InventoryItem inventoryItem = getInventoryItem(dispatchSn);
vOrderSn = generateVOrderSn();
Product product = getProduct(dispatchSn)
doInventoryLoss(inventoryItem, user, inventoryItem.getFacilityId, vOrderSn, product.getGoodName(), inventoryItem.getUnitCost)
}
}
class InventoryService {
void doInventoryLoss(InventoryItem inventoryItem, String user, String facilityId, String vOrderSn, String goodName, String goodPrice){
//处理业务500行
}
}
方案:迪米特法则,接口只传递必要参数,精简参数列表
Divergent Change (多种变化)
class OrderServiceImpl {
Order createSaleOrder(...);
Order createPurchaseOrder(...);
Order createStockOrder(...);
void saleOrderPay();
void saleOrderConfirm();
void purchaseOrderStockIn();
void stockOrderStockIn();
}
方案:拆分成不同类,各自负责某个方向
class OrderFactory {
Order createSaleOrder(...);
Order createPurchaseOrder(...);
Order createStockOrder(...);
}
class OrderService {
void saleOrderPay();
void saleOrderConfirm();
void purchaseOrderStockIn();
void stockOrderStockIn();
}
class SaleOrderService {
Order createSaleOrder(...);
void saleOrderPay();
void saleOrderConfirm();
}
class InventoryOrderService {
Order createPurchaseOrder(...);
Order createStockOrder(...);
void purchaseOrderStockIn();
void stockOrderStockIn();
}
Shotgun Surgery(霰弹式改动)
public void businessA(){
...200行
//库存-供应商退货
...300行
}
public void businessB(){
...200行
//库存-入库
...300行
}
public void businessD(){
...200行
//库存-出库
...300行
}
public void businessE(){
...200行
//库存-盘亏
...300行
}
public void businessF(){
...200行
//库存-盘盈
...300行
}
方案:单一职责, 把一类事情交给一个类来处理
class InventoryService {
public void suppleirReturn(){
//库存-供应商退货
}
public void inStock(){
//库存-入库
}
public void outStock(){
//库存-出库
}
public void loss(){
//库存-盘亏
}
public void regain(){
//库存-盘盈
}
}
public void businessA(){
...200行
inventoryService.suppleirReturn();
...300行
}
public void businessB(){
...200行
inventoryService.inStock();
...300行
}
public void businessD(){
...200行
inventoryService.outStock();
...300行
}
public void businessE(){
...200行
inventoryService.loss();
...300行
}
public void businessF(){
...200行
inventoryService.regain();
...300行
}
参考书目
- 《java与模式》
- 《重构:改善既有代码的设计》
- 《重构与模式》
网友评论