关于设计模式:设计模式之-外观模式

0x01:外观模式简介

外观模式(又称门面模式),通过外观的包装,使应用程序只能看到外观对象,而不会看到具体的细节对象,这样无疑会升高应用程序的复杂度,并且进步了程序的可维护性。UML类图如下:

其中Facade是外观角色,也叫门面角色,客户端能够调用这个角色的办法,此角色通晓子系统的所有性能和责任,将客户端的申请代理给适当的子系统对象;

Subsystem是子系统角色,能够同时领有一个或多个子系统,每一个子系统都不是一个独自的类,而是一个类的汇合,子系统并不知道门面的存在。

0x02:外观模式的实现

定义子系统Subsystem

public class SubSystemA {

    public void dosomethingA() {
        System.out.println("SubSystemA dosomethingA");
    }

}

public class SubSystemB {

    public void dosomethingB() {
        System.out.println("SubSystemB dosomethingB");
    }

}

外观角色Facade

public class Facade {

    //被委托的对象
    private SubSystemA a;

    private SubSystemB b;

    public Facade() {
        a = new SubSystemA();
        b = new SubSystemB();
    }

    //提供给内部拜访的办法
    public void methodA() {
        this.a.dosomethingA();
    }

    public void methodB() {
        this.b.dosomethingB();
    }

}

测试代码

public class Client {

    public static void main(String[] args) {
        Facade facade = new Facade();

        facade.methodA();
        facade.methodB();
    }

}

0x03:利用

因为程序员薪资广泛绝对较高,所以个别有些小钱。那如何进行财产治理呢?本人购买股票呢?又不能很好的把握交易点,常常被人割韭菜。那还有什么治理财产的渠道吗?购买基金就是一个不错的渠道。

股票、国债、期货类

public class Stock{

    //买股票
    public void buy() {
        System.out.println("股票1买入");
    }

    //卖股票
    public void sell() {
        System.out.println("股票1卖出");
    }

}


public class NationalDebt{

    //买国债
    public void buy() {
        System.out.println("国债1买入");
    }

    //卖国债
    public void sell() {
        System.out.println("国债1卖出");
    }

}


public class Futures{

    //买期货
    public void buy() {
        System.out.println("期货1买入");
    }

    //卖期货
    public void sell() {
        System.out.println("期货1卖出");
    }

}

基金类

基金经理人通过该类作为两头交互者,能够接受投资者的资金,对立对股票、国债、期货进行购买和赎回操作。

public class Fund {

    private Stock stock;

    private NationalDebt nationalDebt;

    private Futures futures;

    public Fund() {
        stock = new Stock(); //配置30%
        nationalDebt = new NationalDebt(); //配置60%
        futures = new Futures(); //配置20%
    }

    //购买基金
    public void buyFund() {
        stock.buy();
        nationalDebt.buy();
        futures.buy();
    }

    //赎回基金
    public void sellFund() {
        stock.sell();
        nationalDebt.sell();
        futures.sell();
    }

}

下面这是一个基金,它配置了30%的股票+60%的国债+20%期货。

程序员购买和赎回基金操作

public class Client {

    public static void main(String[] args) {
        Fund fund = new Fund();
        //基金购买
        fund.buyFund();
        System.out.println("》》》》》》》》》》》》");
        //基金赎回
        fund.sellFund();
    }

}

这样的话,再也不怕炒股被割韭菜了。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理