我试图在C#上实现观察者模式,想知道我做得对吗?

时间:2018-05-21 19:31:34

标签: observers

我对观察者模式非常新,认为在某些情况下它非常有用,所以我写了一个简单的项目,我不确定我是否以正确的方式做到了,任何建议都将是赞赏。

class Program
    {
        public delegate void ProductAddedEventHandler(Object sender, ProductAddedEventArgs e);

        public class Products
        {
            private double subtotal;
            public event ProductAddedEventHandler ProductAdded;

            public void Add(Product product)
            {
                ProductModels model = new ProductModels();
                IEnumerable<Product> products = model.Products();
                IEnumerable<Product> new_Collection = products.Concat(new List<Product>() { product });

                Calculate calculate = new Calculate();
                this.subtotal = calculate.create(new_Collection);

                if (ProductAdded != null)
                {
                    ProductAddedEventArgs e = new ProductAddedEventArgs(subtotal);
                    ProductAdded(this, e);
                }

                Console.WriteLine("Subtotal Amount: {0}", subtotal);
            }
        }

        /// <summary>
        /// Calculate the Subtotal
        /// </summary>
        public class Calculate
        {
            public double create(IEnumerable<Product> products)
            {
                double result = 0;
                foreach (Product p in products)
                {
                    result += p.Price;
                }

                return result;
            }
        }

        public class ProductAddedEventArgs : EventArgs
        {
            public readonly double SubTotal;
            public ProductAddedEventArgs(double subtotal) => SubTotal = subtotal;
        }

        public class Shipping
        {
            const double Shipping_Rate = 0.05;

            public void create(Object sender, ProductAddedEventArgs e)
            {
                Console.WriteLine("Shipping Amount: {0}", e.SubTotal * Shipping_Rate);
            }
        }

        public class Discount
        {
            const double Discount_Rate = 0.2;
            public void create(Object sender, ProductAddedEventArgs e)
            {
                Console.WriteLine("Discount Amount: {0}", e.SubTotal * Discount_Rate);
            }
        }

        public class Tax
        {
            const double Tax_Rate = 0.07;

            public void create(Object sender, ProductAddedEventArgs e)
            {
                Console.WriteLine("Tax Amount: {0}", e.SubTotal * Tax_Rate);
            }
        }

        static void Main(string[] args)
        {

            Products products = new Products();
            Shipping shipping = new Shipping();
            Discount discount = new Discount();
            Tax tax = new Tax();

            products.ProductAdded += shipping.create;
            products.ProductAdded += discount.create;
            products.ProductAdded += tax.create;

            products.Add(new Product()
            {
                Id = 50,
                Name = "Watermelon",
                Price = 9.21
            });

        }
    }

BTW,如何获得总金额?

1 个答案:

答案 0 :(得分:1)

虽然这个问题属于https://codereview.stackexchange.com/,但我会尝试写一个简短的答案。

来自DoFactory(GOF)的Observer模式的定义,

  

Observer模式定义了对象之间的一对多依赖关系,这样当一个对象更改状态时,其所有依赖关系都会自动得到通知和更新。

在您的示例中,您没有定义任何观察者,而是您拥有正在更改对象本身状态的事件。在Add()方法中有太多的责任或工作。

观察者的例子可以是购物车(电子商务),例如当产品计数发生变化时,订单汇总对象应该知道它并重新计算汇总(税收,折扣,总额等)。请参阅以下示例,将购物车和订单摘要更新为购物车项目的观察者。它并不完美,但它会给你一个观察者模式的概念:

class Product
{
    // Product properties
}

class ProductCollection
{
    private List<Observer> _observers = new List<Observer>();
    List<Product> _internalcol = new List<Product>();

    public void Attach(Observer observer)
    {
      _observers.Add(observer);
    }

    public void Detach(Observer observer)
    {
      _observers.Remove(observer);
    }

    public void Add(Product p)
    {
        _internalcol.Add(p)
        Notify();
    }

    public void Remove(Product p)
    {

    }

    private void Notify()
    {
      foreach (Observer o in _observers)
      {
        o.Update();
      }
    }
}

class Cart
{
    public ProductionCollection products = new ProductionCollection();
    public OrderSummary summary = new OrderSummary();

    public Cart()
    {
        products.Attach(new OrderSummary(products));
    }

    public void AddProduct(Product p, int count)
    {
        if(count > 1){
            foreach(int i in count){
                products.Add(p);
            }
        else if(count == 1){
            products.Add(p);
        }
        else if(count == 0)
        {
            products.Remove(p);
        }
    }
}

abstract class Observer()
{
    abstract void Update();
}

class OrderSummary: Observer
{
    ProductionCollection _products;

     // Constructor
    public OrderSummary(ProductionCollection products)
    {
        this._products = products;
    }

    public override void Update()
    {
      //Recalculate taxes, discount etc. here.
      // Update Summary object
    }

    public void GetSummary()
    {
        // return/print Summary object;
    }
}

class program
{
        static void Main(string[] args)
        {
            Cart c = new Cart();
            c.products.AddProduct(
                new Product()
                {
                    Id = 50,
                    Name = "Watermelon",
                    Price = 9.21
                });
        }
}

我可能无法编译,我在记事本中写了它。

相关问题