mardi 28 mai 2019

Decorator pattern for a Customer class

Suppose I have a Customer class. A customer can have multiple kinds of loyalty points. For one promotion, the customer may be collecting Rewards. In another, the customer may be collecting Miles. And there is no fixed number of kinds of loyalty points that the Customer is built for. I am sure this is a common use case. Is the decorator pattern a good fit given below sample code?

    public interface ICustomer
    {
        void Display();
    }

    public class SimpleCustomer : ICustomer
    {
        public void Display()
        {
            Console.WriteLine("I am simple customer");
        }
    }

    public abstract class CustomerDecorator : ICustomer
    {
        protected ICustomer customer;

        public CustomerDecorator(ICustomer customer)
        {
            this.customer = customer ?? throw new ArgumentNullException("customer");
        }

        public abstract void Display();
    }

    public class RewardsDecorator : CustomerDecorator
    {
        private int rewards;
        public RewardsDecorator(ICustomer customer, int rewards) : base(customer)
        {
            this.rewards = rewards;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + rewards.ToString() + " rewards");
        }
    }

    public class MilesDecorator : CustomerDecorator
    {
        private int miles;
        public MilesDecorator(ICustomer customer, int miles) : base(customer)
        {
            this.miles = miles;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + miles.ToString() + " miles");
        }
    }

Aucun commentaire:

Enregistrer un commentaire