Welcome to the Csdn-markdown Editor

Source: Internet
Author: User

The opening and closing principle is one of the most important principles of software design, and the design of a business architecture with good extensibility relies heavily on this principle. Business varieties in the increase, already has the business itself is also developing, need to design a unified, flexible, mutual independent business structure. The author in several projects, many times the use of new leadership design Model to design a scalable business structure, I think it is necessary to summarize, for everyone's reference. It was intended to classify the model as one of 23 design patterns, probably due to limited capacity and failed to succeed.

New leadership, grasp the overall situation (the main process), work enlightened. The new style of leadership design is the author of a joke called, only hope easy to remember.

Worst-practice

I've seen countless if else in n projects, one for each business category, and another if, no process, no extension points, everything stuck in a class. Doing better will take several common methods (this is code reuse, not extensible). There may be classmates who refute, "I never design, will not write such code." But I do not believe you have not seen, or passively write a similar code (historical baggage). Anyway, I passively wrote, Want to cry rhythm ...

Ideal State

The manager leads the whole, controls the process, and in the specific task processing, gives (entrusts) the appropriate person to do.
Processes and processes on some common processing is closed, task processing is open, a business to a processor operation, b business to the B processor operation. As follows:

Processes should be handled by systems similar to the workflow engine, and scalability issues can be solved with the new leadership model.

New Leadership Design Model

The new type of leadership design mode should solve two problems.
First, how does the manager organize multiple employee groups? The employee can be saved with a list. How to find employee, preferably through scan (scan) or registration method. Second, how to put the right tasks to the right people to deal with? Give decision-making power to Employee,manager ask who can handle it? Who will hand over the hands first?

Well, the new leadership model works as follows: The manager receives a task, asking each of his employees, who can handle the task, evaluating and giving back to the manager for the task, or not. Hand over the task to the employee who gave the yes.
The class diagram is as follows:

An example

There are many types of investment in the investment market, such as bonds, equities, real estate, funds, trusts, insurance and so on, collectively referred to as assets, and may need to support more investment in the future. Now to design an asset system, one function is to calculate the present value. all assets have this function, but each one can be calculated differently . For simplicity, assume that only bonds and stocks are supported for the time being.

Abstraction of assets
public interface Asset {    /**     * 资产名称     */    String getAssetName();    /**     * 是否固定收益     */    boolean isFixed();}public class BondAsset implements Asset {    @Override    public String getAssetName() {        return "债券";    }    @Override    public boolean isFixed() {        return true;    }}public class StockAsset implements Asset {    @Override    public String getAssetName() {        return "股票";    }    @Override    public boolean isFixed() {        return false;    }}
Processor Abstraction
public interface Handler {    /**     * 是否能够处理该种资产     */    boolean canHandle(Asset asset);    /**     * 计算现值     */    BigDecimal calculateValue(Asset asset);}public class BondHandler implements Handler {    @Override    public boolean canHandle(Asset asset) {        return asset instanceof BondAsset;    }    @Override    public BigDecimal calculateValue(Asset asset) {        // 查询股票数据库的上一收盘价        // 省略N多股票逻辑        return new BigDecimal(100);    }}public class StockHandler implements Handler {    @Override    public boolean canHandle(Asset asset) {        return asset instanceof StockAsset;    }    @Override    public BigDecimal calculateValue(Asset asset) {        // 查询债券数据库的上一收盘日中值        // 省略N多债券逻辑        return new BigDecimal(100);    }}
Unified Invocation Portal
public interface AssetService {    /**     * 计算现值     */    BigDecimal calculateValue(Asset asset);}public class AssetServiceImpl implements AssetService {    @Autowired    private List<Handler> handlers;    @Override    public BigDecimal calculateValue(Asset asset) {        Handler handler = getHandler(asset);        if (handler == null) {            throw new RuntimeException("暂时不支持该类型的资产, 找不到对应的Handler");        }        return handler.calculateValue(asset);    }    /*     * 询问处理器,谁能处理该类型资产     */    private Handler getHandler(Asset asset) {        if (handlers == null || handlers.isEmpty()) {            return null;        }        for (Handler handler : handlers) {            if (handler.canHandle(asset)) {                return handler;            }        }        return null;    }}
Example Supplemental notes
    1. The handlers inside the Assetserviceimpl is injected through the spring @autowired runtime. Other methods include XML configuration registration, API call registration, CLASSPATH scanning, and so on.

    2. The mapping relationship between asset and handler calls GetHandler every time, and if the number of handlers is too large, the efficiency may be worse. You should try other strategies such as HashMap.

    3. In the ideal state, the new assets, only need to implement asset, realize handler can. For example, there is a need to support funds, so write Fundasset and Fundhandler two classes, even configuration is not required. Perfect to reflect the opening and closing principle.

Postscript

The new type of leadership design pattern has the shadow of facade and state design pattern, the unified processing entrance embodies Facade,by context to choose different processing way, embody state. When you need a scalable design, you might want to use it to verify that you throw out the if else of an article.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Welcome to the Csdn-markdown Editor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.