一、引言

每逢去吃午饭路上,几个同事都要讨论一番投资理财的事情,时间久之,小白的我才勉强了解到股票与基金的区别,股票是自身直接与某只股票交易,可以通过分红或者低买高卖获利(自身需要分析股市多只股票的行情,如图示一);而基金是把钱交给基金公司,有专业人员帮你分析股市或债券等帮你理财(自身不需要直接关注股市了,见图示二)。

面向对象编程思想-外观模式

                    图示一

面向对象编程思想-外观模式

                     图示二

在软件开发中,客户端系统经常会与复杂系统的内部子系统进行耦合,从而导致客户端系统随着子系统的改变而改变,为了让客户端系统与复杂系统的内部子系统解耦,从而有了外观模式,也称作“门面模式”,下面将介绍我们今天学习的外观模式:

二、外观模式的结构

外观角色(Facade):被客户client调用,知道各个子系统的功能,根据客户的需要预订几种功能的组合

子系统角色(subsystem):完成子系统功能,处理由facade对象分派的任务。对于子系统而言,facade和client角色是未知的

客户角色(client):通过调用facade完成相应的功能

面向对象编程思想-外观模式

三、外观模式

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

介绍了外观模式的定义,下面我们通过两个例子的对比分析帮助理解外观模式,先看一下不使用外观模式时的投资理财demo

    //子系统  股票一
    class Subsystem1
    {
        public void Buy()
        {
            Console.WriteLine(string.Format("执行{0}中的方法{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
        }
        public void Sell()
        {
            Console.WriteLine(string.Format("执行{0}中的方法{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
        }
    }
    //子系统 股票二
    class Subsystem2
    {
        public void Buy()
        {
            Console.WriteLine(string.Format("执行{0}中的方法{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
        }
        public void Sell()
        {
            Console.WriteLine(string.Format("执行{0}中的方法{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
        }
    }
    //子系统 股票三
    class Subsystem3
    {
        public void Buy()
        {
            Console.WriteLine(string.Format("执行{0}中的方法{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
        }
        public void Sell()
        {
            Console.WriteLine(string.Format("执行{0}中的方法{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
        }
    }
      //客户端调用   
     class Program
    {
        //投资者需要清楚每只股票的行情 
        static void Main(string[] args)
        {
            Subsystem1 system1 = new Subsystem1();
            Subsystem2 system2 = new Subsystem2();
            Subsystem3 system3 = new Subsystem3();
            system1.Buy();
            system2.Buy();
            system3.Buy();
            system1.Sell();
            system2.Sell();
            system3.Sell();
            Console.Read();
        }
    }        
View Code

相关文章: