Friday, June 7, 2013

Facade Design Patterns in C#

Facade: Used to provide a simpler interface into a more complicated portion of code.
class Program
    {
        static void Main(string[] args)
        {
            //Facade
            Mortgage mortgage = new Mortgage();

            //Evaluate mortgage eligibility for customer
            Customer customer = new Customer("paramesh");
            bool eligible = mortgage.IsEligible(customer, 5000);
            Console.WriteLine("\n" + customer.Name + " has been " + (eligible ? "Approved" : "Rejected"));

            Console.ReadKey();
        }
    }

    class Bank
    {
        public bool HasSufficiantSavings(Customer c, int amount)
        {
            Console.WriteLine("Check bank for " + c.Name);
            return true;
        }
    }
    class Credit
    {
        public bool HasGoodCredit(Customer c)
        {
            Console.WriteLine("Check credit for " + c.Name);
            return true;
        }
    }
    class Loan
    {
        public bool NoBadLoans(Customer c)
        {
            Console.WriteLine("Check loans for " + c.Name);
            return true;
        }
    }

    class Customer
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public Customer(string name)
        {
            this._name = name;
        }
    }

    //Facade class
    class Mortgage
    {
        private Bank _bank = null;
        private Loan _loan = null;
        private Credit _credit = null;

        public Mortgage()
        {
            _bank = new Bank();
            _credit = new Credit();
            _loan = new Loan();
        }
        public bool IsEligible(Customer cust, int amount)
        {
            Console.WriteLine("{0} applies for {1} loan\n", cust.Name, amount);
            bool eligible = true;

            //Check creditworthyness of applicant
            if (_bank.HasSufficiantSavings(cust, amount))
            {
                eligible = false;
            }
            else if(!_loan.NoBadLoans(cust))
            {
                eligible = false;
            }
            else if(!_credit.HasGoodCredit(cust))
            {
                eligible = false;
            }
            return eligible;
        }
    }

No comments:

Post a Comment