Administrator
发布于 2024-08-05 / 36 阅读
0
0

外观模式

问题描述

新手炒股很容易亏钱,基金可以将投资着分散的基金集中起来,交给专业的经理人管理和投资。

投资者与众多股票的联系过多,反而不利于操作。有了基金后,投资者只需要和基金打交道,降低了耦合度。

代码实现

股票1、2、3的具体类

public class Stock1
{ 
    public void Buy()
    {
        Console.WriteLine("股票1买入");
    }
    public void Sell()
    {
        Console.WriteLine("股票1卖出");
    }
}

public class Stock2
{
    public void Buy()
    {
        Console.WriteLine("股票2买入");
    }
    public void Sell()
    {
        Console.WriteLine("股票2卖出");
    }
}

public class Stock3
{
    public void Buy()
    {
        Console.WriteLine("股票3买入");
    }
    public void Sell()
    {
        Console.WriteLine("股票3卖出");
    }
}

房地产1的具体类

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

国债1的具体类

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

基金类:

public class Fund
{
    Stock1 gu1;
    Stock2 gu2;
    Stock3 gu3;
    NationalDebt1 nd1;
    Realty1 rt1;

    public Fund()
    {
        gu1 = new Stock1();
        gu2 = new Stock2();
        gu3 = new Stock3();
        nd1 = new NationalDebt1();
        rt1 = new Realty1();
    }

    public void BuyFund()
    {
        gu1.Buy();
        gu2.Buy();
        gu3.Buy();
        nd1.Buy();
        rt1.Buy();
    }

    public void SellFund()
    {
        gu1.Sell();
        gu2.Sell();
        gu3.Sell();
        nd1.Sell();
        rt1.Sell();
    }
}

客户端方法

    internal class Program
    {
        static void Main(string[] args)
        {
            Fund fund = new Fund();
            fund.BuyFund();
            fund.SellFund();
        }
    }

运行结果

股票1买入
股票2买入
股票3买入
国债1买入
房地产1买入
股票1卖出
股票2卖出
股票3卖出
国债1卖出
房地产1卖出

UML图


评论