Exemplo n.º 1
0
 public Teacher()
 {
     Subjects       = new List <Subject>();
     SchoolClasses  = new List <SchoolClass>();
     Advertisements = new List <Advertisement>();
     FaceImage      = new ProxyImage();
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            ProxyImage proxy = new ProxyImage("/etc/img.png");

            proxy.Display();
            proxy.Display();
        }
Exemplo n.º 3
0
        public void Main()
        {
            IImage image = new ProxyImage("test_img_01.jpg");

            // 图像将从磁盘加载
            image.Display();
            // 图像不需要从磁盘加载  缓存了
            image.Display();
        }
Exemplo n.º 4
0
        public void Start()
        {
            var image = new ProxyImage(@"V:\Client\WPF\BuildProj\BuildProj\Resources\Images\AV.png");

            // Image will be loaded from disk.
            image.Display();
            // Image will not be loaded from disk.
            image.Display();
        }
        public static void InvokeProxy()
        {
            IImage image = new ProxyImage("imagemTeste.jpg");

            image.display();
            Console.WriteLine("");
            image.display();
            Console.ReadLine();
        }
Exemplo n.º 6
0
        public static void Test()
        {
            var image1 = new ProxyImage("HiRes_10MB_Photo1");
            var image2 = new ProxyImage("HiRes_10MB_Photo2");

            image1.DisplayImage(); // loading necessary
            image1.DisplayImage(); // loading unnecessary
            image2.DisplayImage(); // loading necessary
            image2.DisplayImage(); // loading unnecessary
            image1.DisplayImage(); // loading unnecessary
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            Image image = new ProxyImage("test_10mb.jpg");

            //image will be loaded from disk
            image.Display();
            Console.WriteLine();

            //image will not be loaded from disk
            image.Display();
        }
Exemplo n.º 8
0
        public void TestProxy()
        {
            IImage image1 = new ProxyImage("HiRes_10MB_Photo1");
            IImage image2 = new ProxyImage("HiRes_10MB_Photo2");

            image1.DisplayImage(); // loading necessary
            image1.DisplayImage(); // loading unnecessary
            image2.DisplayImage(); // loading necessary
            image2.DisplayImage(); // loading unnecessary
            image1.DisplayImage(); // loading unnecessary
        }
Exemplo n.º 9
0
        private void btProxyPattern_Click(object sender, EventArgs e)
        {
            string str   = "";
            IImage image = new ProxyImage("test_10mb.jpg");

            //图像将从磁盘加载
            str += image.display() + "\r\n";
            //图像将无法从磁盘加载
            str += image.display() + "\r\n";
            tbOutWindow.Text = str;
        }
        public void ImageTest()
        {
            IImageLoader loader = new ProxyImage();

            // Loads the image from the file system
            Assert.AreEqual(FileType.Test, loader.GetImage(FileType.Test).GetImageType);

            // Loads the same image but from the dictionary
            Assert.AreEqual(FileType.InMap, loader.GetImage(FileType.Test).GetImageType);

            // Loads the image from the file system
            Assert.AreEqual(FileType.NotInMap, loader.GetImage(FileType.NotInMap).GetImageType);
        }
Exemplo n.º 11
0
        public void Test_virtual_proxy()
        {
            IImage image1 = new ProxyImage("Tiger image");

            Console.WriteLine("Image is loaded for the first time:");
            image1.DisplayImage();// load necessary

            Console.WriteLine("Image is loaded for the second time:");
            image1.DisplayImage();// load unnecessary

            Console.WriteLine("Image is loaded for the thrird time:");
            image1.DisplayImage();// load unnecessary

            IImage Image2 = new ProxyImage("Lion Image");

            Console.WriteLine("Image2 calling DisplayImage first time :");
            Image2.DisplayImage(); // loading necessary

            Console.WriteLine("Image2 calling DisplayImage second time :");
            Image2.DisplayImage(); // loading unnecessary
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            string srcImagePath = @"http://dev.mygemplace.com/Content/_Traders/2/jwProducts/8_Ring2_1qK1b.jpg";
            string photoName    = Path.GetFileNameWithoutExtension(srcImagePath);

            MemoryStream   memory    = new MemoryStream();
            HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(srcImagePath);

            using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
            {
                using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
                {
                    reader.BaseStream.CopyTo(memory);
                    //Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
                    //using (FileStream lxFS = new FileStream("34891.jpg", FileMode.Create))
                    //{
                    //    lxFS.Write(lnByte, 0, lnByte.Length);
                    //}
                }
            }

            Bitmap photo;

            try
            {
                photo = new Bitmap(memory);
            }
            catch (ArgumentException e)
            {
                throw new FileNotFoundException(string.Format(" GDIThumbnail generator file[{0}] not found.", srcImagePath), e);
            }

            // Factory Method
            Console.WriteLine();
            Console.WriteLine("[Abstract Factory] Pattern");
            IWidgetFactory abstractFactory = new PMWidgetFactory();
            IWidgetButton  abstractButton  = abstractFactory.CreateWidgetButton();
            IWidgetDialog  abstractDialog  = abstractFactory.CreateWidgetDialog();

            abstractButton.DrawButton();
            abstractDialog.DrawWidget();

            abstractButton.SetLocation();
            abstractDialog.SetTopMost();
            //-------------------

            // FactoryMethod/Virtual Constructor
            Console.WriteLine();
            Console.WriteLine("[FactoryMethod/Virtual Constructor] Pattern");
            Creator          creator    = new ConcreteCreator();
            IAMethodDocument amDocument = creator.CreateDocument();

            amDocument.Open();
            //----------------------------------

            // Builder
            Console.WriteLine("[Builder] Pattern");
            Console.WriteLine();
            Shop            shop    = new Shop();
            IVehicleBuilder builder = new CarBuilder();

            shop.Construct(builder);
            shop.ShowVehicle();
            builder = new VeloByke();
            shop.Construct(builder);
            shop.ShowVehicle();
            //----------------------

            // Facade
            // Provides more simple unified interface instead of few interfaces some subsystem.
            // Subsystem interfaces don't keep references to facade interface.
            Console.WriteLine();
            Console.WriteLine("[Facade] Pattern");
            Facade facade = new Facade();

            facade.MethodA();
            facade.MethodB();
            //-------

            // Flyweight
            // Build a document with text
            Console.WriteLine();
            Console.WriteLine("[Flyweight] Pattern");
            string document = "AAZZBBZB";

            char[]           chars   = document.ToCharArray();
            CharacterFactory factory = new CharacterFactory();

            // extrinsic state
            int pointSize = 10;

            //For each character use a flyweight object
            foreach (char c in chars)
            {
                pointSize++;
                Character character = factory.GetCharacter(c);
                character.Display(pointSize);
            }
            //-----------

            // Proxy
            Console.WriteLine();
            Console.WriteLine("[Proxy] pattern");
            IImage proxy = new ProxyImage();

            proxy.GetSize();
            proxy.Draw();
            //--------


            //Chain Responsibilities
            Console.WriteLine();
            Console.WriteLine("[Chain of Responsibilities] pattern");
            DialogChain dc1          = new DialogChain(null);
            ButtonChain bc1          = new ButtonChain(dc1);
            DialogChain dc2          = new DialogChain(bc1);
            ButtonChain buttonChain2 = new ButtonChain(dc2);
            IRequest    request1     = new Request1();

            ((Request1)request1).Value = "QWE_RTYU";
            buttonChain2.HandleRequest(request1);

            Request2 rq2 = new Request2();

            rq2.Value = "123456";
            buttonChain2.HandleRequest(rq2);

            //----------------------

            // Command
            Console.WriteLine();
            Console.WriteLine("[Command] Pattern");
            List <SourceCommand> srcCmd = new List <SourceCommand>();

            SourceCommand scr1 = new SourceCommand();

            scr1.Command = new OpenCommand(new Receiver1("Star1"));

            SourceCommand scr2 = new SourceCommand();

            scr2.Command = new PasteCommand(new Receiver2("Paste Star 2"));

            srcCmd.Add(scr1);
            srcCmd.Add(scr2);

            TemplatedCommand <string>       templatedCommand = new TemplatedCommand <string>(delegate(string s) { Console.WriteLine("---Delegate command is executed @@@@ {0}", s); });
            TemplatedSourceCommand <string> scr3             = new TemplatedSourceCommand <string>(templatedCommand);

            scr3.ActionInvoke("1111");

            foreach (var sourceCommand in srcCmd)
            {
                sourceCommand.InvokeCommand();
            }
            //---------

            // Interpreter
            string  roman   = "MCMXXVIII";
            Context context = new Context(roman);

            // Build the 'parse tree'
            List <Expression> tree = new List <Expression>();

            tree.Add(new ThousandExpression());
            tree.Add(new HundredExpression());
            tree.Add(new TenExpression());
            tree.Add(new OneExpression());

            // Interpret
            foreach (Expression exp in tree)
            {
                exp.Interpret(context);
            }

            Console.WriteLine("{0} = {1}", roman, context.Output);

            // define booleand expression
            // (true and x) or (y and x)
            Console.WriteLine("----------------------------");
            BooleanExp     expressing;
            BooleanContext boolContext = new BooleanContext();

            expressing = new OrExp(new AndExp(new BooleanConstant("true"), new VariableExp("x")),
                                   new AndExp(new VariableExp("y"), new NotExp("x")));

            boolContext.Assign("x", false);
            boolContext.Assign("y", false);

            Console.WriteLine("Result of boolean interpreter is [{0}]", expressing.Evaluate(boolContext));
            //-------------

            // Iterator
            Console.WriteLine();
            Console.WriteLine("Pattern Iterator");
            ConcreteAggregate aggregate = new ConcreteAggregate();

            aggregate[0] = "Object 1";
            aggregate[1] = "Object 2";
            aggregate[2] = "Object 3";
            aggregate[3] = "Object 4";
            Iterator iter = aggregate.CreateIterator();

            for (object i = iter.First(); !iter.IsDone(); i = iter.Next())
            {
                Console.WriteLine("Current object [{0}]", i);
            }

            //--------------

            // Mediator
            Console.WriteLine();
            Console.WriteLine("Pattern Mediator");

            // parts could be informed about its mediator.
            ConcreteMediator cm = new ConcreteMediator(new Collegue1(), new Collegue2(), new Collegue3());

            cm.Process1AndInform23();
            cm.Process3AndInform1();
            //------------

            // Memento
            Console.WriteLine();
            Console.WriteLine("Pattern Memento");

            SalesProspect salesProspect = new SalesProspect();

            salesProspect.Budget = 45.56;
            salesProspect.Name   = "Super Man";
            salesProspect.Phone  = "45-78-96";

            ProspectMemory prospectMemory = new ProspectMemory();

            prospectMemory.Memento = salesProspect.SaveMemento();

            salesProspect.Budget = 11.11;
            salesProspect.Name   = "Spider Man";
            salesProspect.Phone  = "33-44-55";

            salesProspect.RestoreMemento(prospectMemory.Memento);
            //--------------

            // Observer (Dependents, Publish-Subscriber)
            Console.WriteLine();
            Console.WriteLine("Pattern Observer");

            Subject           subject           = new Subject();
            ConcreteObserver1 concreteObserver1 = new ConcreteObserver1();
            ConcreteObserver2 concreteObserver2 = new ConcreteObserver2();

            subject.Register(concreteObserver1);
            subject.Register(concreteObserver2);
            subject.Register(concreteObserver1);

            subject.NotifyObservers();

            subject.UnRegister(concreteObserver2);
            subject.UnRegister(concreteObserver2);

            subject.NotifyObservers();
            //------------------------------------------

            // State
            Console.WriteLine();
            Console.WriteLine("Pattern State");
            Account account = new Account("Jim Johnson");

            // Apply financial transactions
            account.Deposit(500.0);
            account.Deposit(300.0);
            account.Deposit(550.0);
            account.PayInterest();
            account.Withdraw(2000.00);
            account.Withdraw(1100.00);
            account.Deposit(50000);
            account.PayInterest();


            //------------------------------------------

            // Strategy
            // Client should knew all available strategies.
            Console.WriteLine();
            Console.WriteLine("Pattern Strategy");

            StrategyContext strategyContext = new StrategyContext(null);

            strategyContext.ContextOperationOne();
            strategyContext.ContextOperationTwo();

            strategyContext.Strategy = new ConcreteStrategy();
            strategyContext.ContextOperationOne();
            strategyContext.ContextOperationTwo();

            //------------------------------------------

            // Template Method
            Console.WriteLine();
            Console.WriteLine("Template Method");
            TemplateMethodClass tmc = new ConcreteTemplateMethodClass1();

            tmc.TemplateMethod();
            //------------------------------------------

            // Visitor
            Console.WriteLine();
            Console.WriteLine("Visitor");
            List <INode> elements = new List <INode>();

            elements.Add(new NodeType1()
            {
                Balance = 400, Name = "Qwerty"
            });
            elements.Add(new NodeType1()
            {
                Balance = 333, Name = "QasxzWe"
            });
            elements.Add(new NodeType2()
            {
                CarName = "Mersedes"
            });
            NodeVisitor visitor = new ConcreteNodeVisitor();

            foreach (var element in elements)
            {
                element.Accept(visitor);
            }

            //------------------------------------------

            ThreadTest threadTest = new ThreadTest();

            //threadTest.RunTask();
            threadTest.TestFactory();

            // Unit of Work patternt with Repository pattern
            Console.WriteLine();
            Console.WriteLine("UOW pattern");
            StudentController sc = new StudentController();

            sc.DoAction();

            MoneyPattern.Start();
            Console.Read();
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");



            //#region Factory design pattern
            //ConsoleColorMethod("Factory design pattern");


            //IFactory factory = CreateFactory.GetObject(ObjectType.Customer);
            //Console.WriteLine("Get customer object : " + factory.getName());

            //factory = CreateFactory.GetObject(ObjectType.Supplier);
            //Console.WriteLine("Get supplier object : " + factory.getName());
            //#endregion


            //#region Adapter design pattern
            //IExport target = new PDF_Class();
            //target.Export();

            //target = new XLS_Class_ObjectAdapter();
            //target.Export();

            //target = new XLS_Class_ClassAdapter();
            //target.Export();
            //#endregion

            //#region Builder design pattern

            //// Client Code

            //ReportDirector reportDirector = new ReportDirector();

            //ExcelReport excelReport = new ExcelReport();
            //Report report = reportDirector.MakeReport(excelReport);
            ////report.DisplayReport();

            //#endregion

            #region Decorator design pattern
            IMemoryCache    _memoryCache         = new MemoryCache(new MemoryCacheOptions());
            IWeatherService innerService         = new WeatherService();
            IWeatherService withCachingDecorator = new WeatherServiceCachingDecorator(innerService, _memoryCache);
            IWeatherService withLoggingDecorator = new WeatherServiceLoggingDecorator(withCachingDecorator);

            // with no cache - first time
            Console.WriteLine(withCachingDecorator.GetCurrentWeather("Bangalore"));
            // with cache - second time
            Console.WriteLine(withCachingDecorator.GetCurrentWeather("Bangalore"));


            // with no cache - first time
            Console.WriteLine(withLoggingDecorator.GetCurrentWeather("Bangalore"));
            // with cache - second time
            Console.WriteLine(withLoggingDecorator.GetCurrentWeather("Bangalore"));


            Console.ReadLine();



            #endregion

            //#region Prototype Design Pattern

            //Employee emp1 = new Employee();
            //emp1.Name = "Amit Naik";
            //emp1.Department = "IT";
            //Employee emp2 = emp1.GetClone();
            //emp2.Name = "Shwetha";

            //Console.WriteLine("Emplpyee 1: ");
            //Console.WriteLine("Name: " + emp1.Name + ", Department: " + emp1.Department);
            //Console.WriteLine("Emplpyee 2: ");
            //Console.WriteLine("Name: " + emp2.Name + ", Department: " + emp2.Department);


            //#endregion


            //#region Memento Design Pattern

            //Employee emp1 = new Employee();
            //emp1.Name = "Amit Naik";
            //emp1.Department = "IT";
            //Employee emp2 = emp1.GetClone();
            //emp2.Name = "Shwetha";



            //Console.WriteLine("Emplpyee 1: ");
            //Console.WriteLine("Name: " + emp1.Name + ", Department: " + emp1.Department);
            ////Console.WriteLine("Emplpyee 2: ");
            ////Console.WriteLine("Name: " + emp2.Name + ", Department: " + emp2.Department);

            //Employee emp3 = emp1.Revert();
            //Console.WriteLine("Reverting ");
            //Console.WriteLine("Name: " + emp3.Name + ", Department: " + emp3.Department);

            //#endregion


            //#region Aggregate root design pattern

            //Customer customer = new Customer();

            //customer.Add(new Address { Type = 1 });
            //customer.Add(new Address { Type = 1 });

            //#endregion


            //#region Iterator design pattern

            //Customer customer = new Customer();

            //customer.Add(new Address { Type = 1 });
            //customer.Add(new Address { Type = 2 });

            //// we can avoid manipulating methods like below in Iterator design pattern
            ////customer.addresses.Add(new Address { Type = 3 });


            //// Implementing via Ienumerable
            //foreach (var item in customer.GetAddresses())
            //{
            //    Console.WriteLine($"customer address type  : {item.Type}");
            //}

            //// Implementing via IEnumerator
            //foreach (var item in customer)
            //{
            //    Console.WriteLine($"customer address type  : {item.Type}");

            //}
            ////var x = customer.GetEnumerator();


            //#endregion


            #region Generic Repository Design Pattern


            ConsoleColorMethod("Generic Repository design pattern");

            // Generic
            IGenericRepository <Employee> repository = null;
            repository = new GenericRepository <Employee>();

            try
            {
                var employee = new Employee()
                {
                    Name = "Amit", Salary = 60000, Gender = "Male", Dept = "IT"
                };
                repository.Add(employee);
                repository.Save();

                repository = new GenericRepository <Employee>();
                var id = repository.GetById(1);

                repository = new GenericRepository <Employee>();
                var all = repository.GetAll();

                repository = new GenericRepository <Employee>();
                var id1 = repository.GetById(1);

                if (id1 != null)
                {
                    id1.Name = "Amit Naik";
                    repository.Update(id1);
                    repository.Save();

                    repository = new GenericRepository <Employee>();
                    repository.Delete(1);
                    repository.Save();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Error : ID not found");
                    Console.ForegroundColor = ConsoleColor.White;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Error :{ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            #endregion

            #region Non Generic Repository Design Pattern

            ConsoleColorMethod("Non Generic Repository design pattern");

            // Generic
            EmployeeRepository employeeRepository = null;
            employeeRepository = new EmployeeRepository();

            try
            {
                var employee = new Employee()
                {
                    Name = "Shweta", Salary = 600000, Gender = "Female", Dept = "IT"
                };
                employeeRepository.Add(employee);
                employeeRepository.Save();

                employeeRepository = new EmployeeRepository();
                var id = employeeRepository.GetById(1);

                employeeRepository = new EmployeeRepository();
                var all = employeeRepository.GetAll();

                employeeRepository = new EmployeeRepository();
                var id1 = employeeRepository.GetById(2);

                if (id1 != null)
                {
                    id1.Name = "Shweta Naik";
                    employeeRepository.Update(id1);
                    employeeRepository.Save();

                    employeeRepository = new EmployeeRepository();
                    employeeRepository.Delete(1);
                    employeeRepository.Save();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Error : ID not found");
                    Console.ForegroundColor = ConsoleColor.White;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Error :{ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            #endregion

            #region UOW design pattern for Generic Repository

            ConsoleColorMethod("UOW design pattern for Generic Repository");

            UOW_Generic <Employee> uowG = new UOW_Generic <Employee>(new EmployeeDBContext());

            try
            {
                var employee = new Employee()
                {
                    Name = "Shweta", Salary = 600000, Gender = "Female", Dept = "IT UOW generic"
                };

                uowG.employeeRepository.Add(employee);
                uowG.Complete();
            }
            catch (Exception ex)
            {
                uowG.Dispose();

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Error : {ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            #endregion

            #region UOW design pattern for Non Generic Repository

            ConsoleColorMethod("UOW design pattern for Non Generic Repository");

            UnitOfWork uow = new UnitOfWork(new EmployeeDBContext());

            try
            {
                var employee = new Employee()
                {
                    Name = "Shweta", Salary = 600000, Gender = "Female", Dept = "IT UOW non generic"
                };

                uow.employeeRepository.Add(employee);
                uow.Complete();
            }
            catch (Exception ex)
            {
                uow.Dispose();

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Error : {ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            #endregion

            #region Template design pattern
            ConsoleColorMethod("Template design pattern");

            TemplateHiringProcess hiringProcess = new CSDepartment();

            Console.WriteLine("*** Hiring CS students");
            hiringProcess.HireFreshers();

            Console.WriteLine(Environment.NewLine);

            hiringProcess           = new EEEDepartment();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*** Hiring EEE students");
            hiringProcess.HireFreshers();

            #endregion

            #region Singleton Design Pattern
            ConsoleColorMethod("Singleton design pattern");

            Singleton s1 = Singleton.getInstance();
            Singleton s2 = Singleton.getInstance();

            s1.myMethod();

            // Test for same instance
            //if (s1 == s2)
            //{
            //    Console.WriteLine("Objects are the same instance");
            //}

            #endregion

            #region Replace IF with Polyphormism

            ConsoleColorMethod("Replace IF with Polyphormism");

            Console.WriteLine("Enter your skill set for job opening (like JavaScript,c#,Net)");

            //string knowledge = Console.ReadLine();
            string knowledge = "javascript";

            Console.WriteLine(SimpleFactoryRIP.Create(knowledge.ToLower()));
            #endregion

            #region Abstract Factory design pattern

            ConsoleColorMethod("Abstract Factory design pattern");

            var    investmentPrivateFactory = InvestmentFactory.CreateFactory("Private");
            string productType = investmentPrivateFactory.GetProduct("ICICI").FD(1000);

            Console.WriteLine(productType);

            Console.WriteLine(InvestmentFactory.CreateFactory("Public").GetProduct("SBI").MF(50000));
            #endregion

            #region IOC DI Unity

            ConsoleColorMethod("IOC DI Unity");

            IUnityContainer container = new UnityContainer();
            container.RegisterType <IRechargeHandler, RechargeJIO>("JIO");
            container.RegisterType <IRechargeHandler, RechargeVodafone>("Vodafone");

            IRechargeHandler recharge = container.Resolve <IRechargeHandler>("JIO");
            recharge.DoRecharge();

            #endregion

            #region Lazy loading

            ConsoleColorMethod("Lazy loading");
            Console.WriteLine("Enter your skill set for job opening (like JavaScript,c#,Net)");

            string knowledgeLazyLoading = "Javascript";

            Console.WriteLine(LazyLoadingFactory.Create(knowledgeLazyLoading.ToLower()));

            // When we call second time, it doesn't add to temp Dictionary in LazyLoadingFactory class file
            Console.WriteLine(LazyLoadingFactory.Create(knowledgeLazyLoading.ToLower()));

            #endregion



            #region Bridge design pattern

            ConsoleColorMethod("Bridge design pattern");
            Payment order = new CardPayment();
            order.IPaymentSystem = new CitiPaymentSystem();
            order.MakePayment();

            order.IPaymentSystem = new ICICIPaymentSystem();
            order.MakePayment();

            order = new NetBankingPayment();
            order.IPaymentSystem = new CitiPaymentSystem();
            order.MakePayment();
            #endregion


            #region Composite design pattern
            ConsoleColorMethod("Composite design pattern");
            IEmployeeCDP John  = new EmployeeCDP("John", "IT");
            IEmployeeCDP Mike  = new EmployeeCDP("Mike", "IT");
            IEmployeeCDP Jason = new EmployeeCDP("Jason", "HR");
            IEmployeeCDP Eric  = new EmployeeCDP("Eric", "HR");
            IEmployeeCDP Henry = new EmployeeCDP("Henry", "HR");

            IEmployeeCDP James = new ManagerCDP("James", "IT")
            {
                SubOrdinates = { John, Mike }
            };
            IEmployeeCDP Philip = new ManagerCDP("Philip", "HR")
            {
                SubOrdinates = { Jason, Eric, Henry }
            };

            IEmployeeCDP Bob = new ManagerCDP("Bob", "Head")
            {
                SubOrdinates = { James, Philip }
            };
            James.GetDetails(1);
            #endregion


            #region Facade design pattern
            ConsoleColorMethod("Facade design pattern");

            AadharFacade aadharFacade = new AadharFacade();
            aadharFacade.CreateAadhar();
            #endregion

            #region Chain of Responsibility design pattern
            ConsoleColorMethod("Chain of Responsibility design pattern");
            NewVehicle selection   = new SelectVehicle();
            NewVehicle payment     = new MakePayment();
            NewVehicle serviceBook = new GenerateServiceBook();
            NewVehicle insurance   = new Insurance();
            NewVehicle delivery    = new Delivery();

            selection.SetProcess(payment);
            payment.SetProcess(serviceBook);
            serviceBook.SetProcess(insurance);
            insurance.SetProcess(delivery);

            selection.Proceed("Bajaj Pulsar");
            #endregion


            #region Strategy design pattern
            ConsoleColorMethod("Strategy design pattern");
            HashingContext context;

            context = new HashingContext(new MD5Hash());
            string strSHA1 = context.HashPassword("Amit Naik");
            Console.WriteLine("Amit Naik - " + strSHA1);

            context = new HashingContext(new SHA384Hash());
            string StrSHA384 = context.HashPassword("Shwetha Naik");
            Console.WriteLine("Shwetha Naik - " + StrSHA384);

            #endregion


            #region Strategy design pattern
            ConsoleColorMethod("Strategy design pattern");
            IImage Image1 = new ProxyImage("Tiger Image");

            Console.WriteLine("Image1 calling DisplayImage first time :");
            Image1.DisplayImage(); // loading necessary
            Console.WriteLine("Image1 calling DisplayImage second time :");
            Image1.DisplayImage(); // loading unnecessary
            Console.WriteLine("Image1 calling DisplayImage third time :");
            Image1.DisplayImage(); // loading unnecessary
            Console.WriteLine();
            IImage Image2 = new ProxyImage("Lion Image");
            Console.WriteLine("Image2 calling DisplayImage first time :");
            Image2.DisplayImage(); // loading necessary
            Console.WriteLine("Image2 calling DisplayImage second time :");
            Image2.DisplayImage(); // loading unnecessary

            #endregion

            #region Strategy design pattern
            ConsoleColorMethod("Strategy design pattern");

            //Create a Product with Out Of Stock Status
            Subject IPhone = new Subject("IPhone Mobile", 10000, "Out Of Stock");
            //User Anurag will be created and user1 object will be registered to the subject
            Observer user1 = new Observer("Amit", IPhone);
            //User Pranaya will be created and user1 object will be registered to the subject
            Observer user2 = new Observer("Shweta", IPhone);
            //User Priyanka will be created and user3 object will be registered to the subject
            Observer user3 = new Observer("Krishna", IPhone);

            Console.WriteLine("IPhone Mobile current state : " + IPhone.getAvailability());
            Console.WriteLine();
            // Now product is available
            IPhone.setAvailability("Available");
            #endregion


            #region State design pattern
            ConsoleColorMethod("State design pattern");

            // Initially Vending Machine will be 'noMoneyState'
            VendingMachine vendingMachine = new VendingMachine();
            Console.WriteLine("Current VendingMachine State : "
                              + vendingMachine.vendingMachineState.GetType().Name + "\n");
            vendingMachine.DispenseProduct();
            vendingMachine.SelectProductAndInsertMoney(50, "Pepsi");
            // Money has been inserted so vending Machine internal state
            // changed to 'hasMoneyState'
            Console.WriteLine("\nCurrent VendingMachine State : "
                              + vendingMachine.vendingMachineState.GetType().Name + "\n");
            vendingMachine.SelectProductAndInsertMoney(50, "Fanta");
            vendingMachine.DispenseProduct();
            // Product has been dispensed so vending Machine internal state
            // changed to 'NoMoneyState'
            Console.WriteLine("\nCurrent VendingMachine State : "
                              + vendingMachine.vendingMachineState.GetType().Name);
            #endregion
        }
Exemplo n.º 14
0
        static void Main()
        {
            Image image = new ProxyImage("fileName.png");

            image.display();
        }
Exemplo n.º 15
0
        public void WhenProxyImageWillReturnProxyResult()
        {
            var image = new ProxyImage("Picture.jpg");

            Assert.AreEqual("Displaying Picture.jpg", image.Display());
        }