外观模式

《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。
目录:设计模式
Github地址:DesignPattern

说明

定义:外观模式(Facade),为系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

UML图:

这里写图片描述

代码实现:

四个子系统的类

class SubSystemOne{
    public void MethodOne(){
        System.out.println("子系统方法一");
    }
}
class SubSystemTwo{
    public void MethodTwo(){
        System.out.println("子系统方法二");
    }
}
class SubSystemThree{
    public void MethodThree(){
        System.out.println("子系统方法三");
    }
}
class SubSystemFour{
    public void MethodFour(){
        System.out.println("子系统方法四");
    }
}

外观类

class Facade{
    SubSystemOne one;
    SubSystemTwo two;
    SubSystemThree three;
    SubSystemFour four;

    public Facade(){
        one = new SubSystemOne();
        two = new SubSystemTwo();
        three = new SubSystemThree();
        four = new SubSystemFour();
    }

    public void MethodA(){
        System.out.println("方法组A()");
        one.MethodOne();
        two.MethodTwo();
        four.MethodFour();
    }

    public void MethodB(){
        System.out.println("方法组B()");
        two.MethodTwo();
        three.MethodThree();
    }
}

客户端代码

public class FacadePattern {
    public static void main(String[] args){
        Facade facade = new Facade();
        facade.MethodA();
        facade.MethodB();
    }
}

运行结果

方法组A()
子系统方法一
子系统方法二
子系统方法四
方法组B()
子系统方法二
子系统方法三

示例

例子:股民在炒股的时候经常会面对众多股票不知道如何买进卖出,这个时候就有了基金,客户只需要看好基金,然后通过买进卖出一支基金,让基金去选购股票或者其他投资方式就好了。这个过程用程序该如何实现?

UML图:

这里写图片描述

代码实现:

股票1,股票2,国债1代码类似

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

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

基金类

public class Fund {
    Stock1 stock1;
    Stock2 stock2;
    NationalDebt1 nationalDebt1;

    public Fund(){
        stock1 = new Stock1();
        stock2 = new Stock2();
        nationalDebt1 = new NationalDebt1();
    }

    public void BuyFund(){
        stock1.Buy();
        stock2.Buy();
        nationalDebt1.Buy();
    }

    public void SellFund(){
        stock1.Sell();
        stock2.Sell();
        nationalDebt1.Sell();
    }
}

客户端代码

public class Main {
    public static void main(String[] args){
        Fund fund = new Fund();
        //基金购买
        fund.BuyFund();
        //基金赎回
        fund.SellFund();
    }
}

运行结果

股票1买入
股票2买入
国债1买入
股票1卖出
股票2卖出
国债1卖出
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值