设计模式(八)——外观模式

来源:互联网 发布:匿名网络短信发送平台 编辑:程序博客网 时间:2024/06/05 18:35

外观模式(Facade)

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

代码

我们以一个股票投资的程序来阐述外观模式:
1.代码如下:

股票类

using System;namespace Facade{//股票1public class Stock1{//买股票public void Sell(){Console.WriteLine ("股票1卖出");}//买股票public void Buy(){Console.WriteLine ("股票1买入");}}}
using System;namespace Facade{//股票2public class Stock2{//买股票public void Sell(){Console.WriteLine ("股票2卖出");}//买股票public void Buy(){Console.WriteLine ("股票2买入");}}}
using System;namespace Facade{//股票3public class Stock3{//买股票public void Sell(){Console.WriteLine ("股票3卖出");}//买股票public void Buy(){Console.WriteLine ("股票3买入");}}}

国债类

using System;namespace Facade{//国债1public class NationalDebt1{//买国债public void Sell(){Console.WriteLine ("国债1卖出");}//买国债public void Buy(){Console.WriteLine ("国债1买入");}}}

房地产类

using System;namespace Facade{//房地产1public class Realty1{//买房地产public void Sell(){Console.WriteLine ("房地产1卖出");}//买房地产public void Buy(){Console.WriteLine ("房地产1买入");}}}

基金类

using System;namespace Facade{//基金类public class Fund{Stock1 stock1;Stock2 stock2;Stock3 stock3;NationalDebt1 nationalDebt1;Realty1 realty1;public Fund(){stock1 = new Stock1 ();stock2 = new Stock2 ();stock3 = new Stock3 ();nationalDebt1 = new NationalDebt1 ();realty1 = new Realty1 ();}//买基金public void BuyFund(){stock1.Buy ();stock2.Buy ();stock3.Buy ();nationalDebt1.Buy ();realty1.Buy ();}//卖基金public void SellFund(){stock1.Sell ();stock2.Sell ();stock3.Sell ();nationalDebt1.Sell ();realty1.Sell ();}}}
2.客户端代码如下

客户端代码

using System;namespace Facade{class MainClass{public static void Main (string[] args){Fund fund = new Fund ();//基金购买fund.BuyFund();//基金赎回fund.SellFund();}}}
3.运行结果

UML图


源码下载地址:https://gitee.com/ZhaoYongshuang/DesignPattern.git