private static void GetPrototypePattern() { Console.WriteLine("***Prototype Pattern***\n"); //Base or Original Copy BasicCar nano_base = new Nano("Green Nano") { Price = 100000 }; BasicCar ford_base = new Ford("Ford Yellow") { Price = 500000 }; BasicCar bc1; //Nano bc1 = nano_base.Clone(); bc1.Price = nano_base.Price + BasicCar.SetPrice(); Console.WriteLine("Car is: {0}, and it's price is Rs. {1}", bc1.ModelName, bc1.Price); //Ford bc1 = ford_base.Clone(); bc1.Price = ford_base.Price + BasicCar.SetPrice(); Console.WriteLine("Car is: {0}, and it's price is Rs. {1}", bc1.ModelName, bc1.Price); Console.ReadLine(); }
static void ExecuteProblem2FactoryPattern() { Honda objHonda = new Honda(); objHonda.GetCarModel(); BMW objBMW = new BMW(); objBMW.GetCarModel(); // If we want to add new class then we need to modify client code also. Nano objNano = new Nano(); objNano.GetCarModel(); }
static void Main(string[] args) { #region Singleton Pattern Singleton s1, s2; s1 = s2 = null; var tasks = new List <Task>(); var t1 = Task.Run(() => { s1 = Singleton.Instanse; }); tasks.Add(t1); var t2 = Task.Run(() => { s2 = Singleton.Instanse; }); tasks.Add(t2); Task.WaitAll(tasks.ToArray()); Console.WriteLine(s1 == s2 ? "Only one instance exist" : "Multiple instance exist"); #endregion #region Prototype Pattern var basicCar = new Nano() { Brand = "Nano", Price = 100000, Engine = "1440 CC", Transmission = "Mannual" }; var car1 = basicCar.Clone(); car1.Price = basicCar.Price + BasicCar.SetPrice(); car1.Transmission = "Automatic"; var car2 = car1.Clone(); car2.Engine = "1668 CC"; car2.Price = car1.Price + BasicCar.SetPrice(); #endregion }
static void Main(string[] args) { //Creational Patterns Console.WriteLine("Creational Patterns"); #region Singleton Console.WriteLine("***Singleton Pattern Demo***\n"); Console.WriteLine("Trying to create instance s1."); Singleton s1 = Singleton.Instance; Console.WriteLine("Trying to create instance s2."); Singleton s2 = Singleton.Instance; if (s1 == s2) { Console.WriteLine("Only one instance exists."); } else { Console.WriteLine("Different instances exists."); } #endregion Console.WriteLine("###########################"); #region Prototype Console.WriteLine("***Prototype Pattern Demo***\n"); //Base or Original BasicCar nano_base = new Nano("Green Nano") { Price = 100000 }; BasicCar ford_base = new Ford("FordYellow") { Price = 500000 }; BasicCar bc1; //Nano bc1 = nano_base.Clone(); bc1.Price = nano_base.Price + BasicCar.SetPrice(); Console.WriteLine($"Car is {bc1.ModelName}, and price is {bc1.Price}"); //Ford bc1 = ford_base.Clone(); bc1.Price = ford_base.Price + BasicCar.SetPrice(); Console.WriteLine($"Car is {bc1.ModelName}, and price is {bc1.Price}"); #endregion Console.WriteLine("###########################"); #region Buuilder Console.WriteLine("***Builder Pattern Demo***"); Director director = new Director(); IBuilder b1 = new Car("Ford"); IBuilder b2 = new MotorCycle("Honda"); //Mking Car director.Construct(b1); Product p1 = b1.GetVehicle(); p1.Show(); //Making Motorcycle director.Construct(b2); Product p2 = b2.GetVehicle(); p2.Show(); #endregion Console.WriteLine("###########################"); #region Factory Method Pattern Console.WriteLine("***Factory Pattern Demo***\n"); // Creating a Tiger Factory AnimalFactory tigerFactory = new TigerFactory(); // Creating a tiger using the Factory Method IAnimal aTiger = tigerFactory.CreateAnimal(); aTiger.AboutMe(); aTiger.Action(); // Creating a DogFactory AnimalFactory dogFactory = new DogFactory(); // Creating a dog using the Factory Method IAnimal aDog = dogFactory.CreateAnimal(); aDog.AboutMe(); aDog.Action(); #endregion Console.WriteLine("###########################"); #region Abstract Factory Pattern Console.WriteLine("***Abstract Factory Pattern Demo***\n"); //Making a wild dog through WildAnimalFactory IAnimalFactory wildAnimalFactory = new WildAnimalFactory(); IDog wildDog = wildAnimalFactory.GetDog(); wildDog.Speak(); wildDog.Action(); //Making a wild tiger through WildAnimalFactory ITiger wildTiger = wildAnimalFactory.GetTiger(); wildTiger.Speak(); wildTiger.Action(); Console.WriteLine("******************"); //Making a pet dog through PetAnimalFactory IAnimalFactory petAnimalFactory = new PetAnimalFactory(); IDog petDog = petAnimalFactory.GetDog(); petDog.Speak(); petDog.Action(); //Making a pet tiger through PetAnimalFactory ITiger petTiger = petAnimalFactory.GetTiger(); petTiger.Speak(); petTiger.Action(); #endregion Console.WriteLine("###########################"); //Structural Patterns Console.WriteLine("Structural Patterns"); #region Proxy Pattern Console.WriteLine("***Proxy Pattern Demo***"); Proxy px = new Proxy(); px.DoSomeWork(); #endregion Console.WriteLine("###########################"); #region Decorator Pattern Console.WriteLine("***Decorator Pattern Simulation***"); ConcreteComponent cc = new ConcreteComponent(); ConcreteDecoratorEx1 decorator1 = new ConcreteDecoratorEx1(); decorator1.SetTheComponent(cc); decorator1.MakeHouse(); ConcreteDecoratorEx2 decorator2 = new ConcreteDecoratorEx2(); //Adding results from decorator1 decorator2.SetTheComponent(decorator1); decorator2.MakeHouse(); #endregion Console.WriteLine("###########################"); #region Adapter Pattern Console.WriteLine("***Adapter Pattern Demo***\n"); CalculatorAdapter cal = new CalculatorAdapter(); Triangle t = new Triangle(20, 10); Console.WriteLine($"Area of Triangle is {cal.GetArea(t)} square unit"); #endregion Console.WriteLine("###########################"); #region Facade Pattern Console.WriteLine("***Facade Pattern Demo***"); RobotFacade robotFacade1 = new RobotFacade(); // Creating Robots robotFacade1.ConstructMilanoRobot(); RobotFacade robotFacade2 = new RobotFacade(); // Creating Robots robotFacade2.ConstructRobonautRobot(); robotFacade1.DestroyMilanoRobot(); //Destroying Robots robotFacade2.DestroyRobonautRobot(); #endregion Console.WriteLine("###########################"); #region Flyweight Pattern Console.WriteLine("***Flyweight Pattern Demo***"); RobotFactory myFactory = new RobotFactory(); IRobot shape = myFactory.GetRobotFromFactory("Small"); shape.Print(); //Creating small robots for (int i = 0; i < 2; i++) { shape = myFactory.GetRobotFromFactory("Small"); shape.Print(); } int numOfDistinctRobots = myFactory.TotalObjectsCreated; Console.WriteLine($"Number of distinct robot objects is {numOfDistinctRobots}"); //Creating large robots for (int i = 0; i < 5; i++) { shape = myFactory.GetRobotFromFactory("Large"); shape.Print(); } numOfDistinctRobots = myFactory.TotalObjectsCreated; Console.WriteLine($"Distinct robot objects created till now {numOfDistinctRobots}"); #endregion Console.WriteLine("###########################"); #region Composite Pattern #region Mathematics department Console.WriteLine("***Composite Pattern***"); //2 Lecturers work in Mathematics department Employee mathLecturer1 = new Employee { Name = "M. Joy", Dept = "Mathematics", Designation = "Lecturer" }; Employee mathLecturer2 = new Employee { Name = "M. Ronny", Dept = "Mathematics", Designation = "Lecturer" }; //The college has Head of Department in Mathematics CompositeEmployee hodMaths = new CompositeEmployee { Name = "Mrs. S. Das", Dept = "Maths", Designation = "HOD-Maths" }; //Lecturers of Mathematics directly perort to HOD-Maths hodMaths.AddEmpployee(mathLecturer1); hodMaths.AddEmpployee(mathLecturer2); #endregion #region Computer Science department //3 lecturers work in Computer Sc. department Employee cseLecturer1 = new Employee { Name = "C. Sam", Dept = "Computer Sciense", Designation = "Lecturer" }; Employee cseLecturer2 = new Employee { Name = "C. Jones", Dept = "Computer Sciense", Designation = "Lecturer" }; Employee cseLecturer3 = new Employee { Name = "C. Marium", Dept = "Computer Sciense", Designation = "Lecturer" }; //The College has a Head of Department in Computer science CompositeEmployee hodCompSc = new CompositeEmployee { Name = "Mr. V. Sarcar", Dept = "Computer Sc.", Designation = "HOD-Computer Sc." }; //Lecturers of Computer Sc. directly reports to HOD-CSE hodCompSc.AddEmpployee(cseLecturer1); hodCompSc.AddEmpployee(cseLecturer2); hodCompSc.AddEmpployee(cseLecturer3); #endregion #region Top level management //College Principial CompositeEmployee principal = new CompositeEmployee { Name = "Dr.S.Som", Dept = "Planning-Supervising-Managing", Designation = "Principal" }; //Mead of Department of Math and Computer Sciense apply to Principal principal.AddEmpployee(hodMaths); principal.AddEmpployee(hodCompSc); #endregion Console.WriteLine("Details of a Principal are these: "); principal.DisplayDetails(); Console.WriteLine("Details of HOD object are these: "); hodCompSc.DisplayDetails(); Console.WriteLine("Details of individual employee are these: "); mathLecturer1.DisplayDetails(); //Lecturer leaves hodCompSc.RemoveEmployee(cseLecturer2); Console.WriteLine("After resignstion there are only these leecturers"); principal.DisplayDetails(); #endregion }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { #region Comment all except this region to check Simple Factory Pattern Demo & Include SimpleFactoryPattern namaspace only //await context.Response.WriteAsync("*** TechWebDots: Simple Factory Pattern Demo***\n\n"); //IAnimal preferredType = null; //ISimpleFactory simpleFactory = new SimpleFactory(); //#region The code region that will vary based on userspreference //await context.Response.WriteAsync("Factory can accept (0 for Dog, 1 for Tiger)\n\n"); //await context.Response.WriteAsync("Passing (0 for Dog) to Create Dog Animal\n\n"); //preferredType = simpleFactory.CreateAnimal(0); //#endregion //await context.Response.WriteAsync("Dog Animal created and Getting Dog Animal Features\n\n"); //#region The codes that do not change frequently //preferredType.Speak(); //preferredType.Action(); //#endregion #endregion #region Comment all except this region to check Factory Method Design Pattern Demo, Include SimpleFactoryPattern & FactoryMethodPattern namaspace only //await context.Response.WriteAsync("*** TechWebDots: Factory Method Design Pattern Demo***\n\n"); //IAnimalFactory dogFactory = new DogFactory(); //#region The code region that will vary based on userspreference //await context.Response.WriteAsync("Dog Factory can create only Dog Animals!\n\n"); //IAnimal aDog = dogFactory.MakeAnimal(); ////IAnimal aDog = dogFactory.CreateAnimal(); //#endregion //await context.Response.WriteAsync("Dog Animal created and Getting Dog Animal Features!\n\n"); //#region The codes that do not change frequently ////aDog.Speak(); ////aDog.Action(); //#endregion #endregion #region Comment all except this region to check Abstract Factory Design Pattern Demo & Include AbstractFactoryPattern namaspace only //await context.Response.WriteAsync("*** TechWebDots: Factory Method Design Pattern Demo***\n\n"); //await context.Response.WriteAsync("*** TechWebDots: Making a wild tiger through WildAnimalFactory ***\n\n"); ////Making a wild tiger through WildAnimalFactory //IAnimalFactory wildAnimalFactory = new WildAnimalFactory(); //ITiger wildTiger = wildAnimalFactory.GetTiger(); //wildTiger.Speak(); //wildTiger.Action(); //await context.Response.WriteAsync("*** TechWebDots: Making a pet dog through PetAnimalFactory ***\n\n"); ////Making a pet dog through PetAnimalFactory //IAnimalFactory petAnimalFactory = new PetAnimalFactory(); //IDog petDog = petAnimalFactory.GetDog(); //petDog.Speak(); //petDog.Action(); #endregion #region Comment all except this region to check Singleton Pattern Demo & Include SingletonPattern namaspace only //await context.Response.WriteAsync("***Singleton Pattern Demo***\n\n"); //await context.Response.WriteAsync("Trying to create instance s1.\n\n"); //Singleton s1 = Singleton.Instance; //await context.Response.WriteAsync("Trying to create instance s2.\n\n"); //Singleton s2 = Singleton.Instance; //if (s1 == s2) //{ // await context.Response.WriteAsync("Only one instance exists.\n\n"); //} //else //{ // await context.Response.WriteAsync("Different instances exist.\n\n"); //} //await context.Response.WriteAsync("***Thread-Safe Singleton Pattern Demo***\n\n"); //SingletonTS sts = SingletonTS.Instance; #endregion #region Comment all except this region to check observer Pattern Demo & Include ObserverPattern namaspace only //await context.Response.WriteAsync("***Observer Pattern Demo***\n"); ////We have 3 observers-2 of them are ObserverType1, 1 of them is of ObserverType2 //IObserver myObserver1 = new ObserverType1("DB Subscriber 1"); //IObserver myObserver2 = new ObserverType1("DB Subscriber 2"); //IObserver myObserver3 = new ObserverType2("DB Subscriber 3"); //Subject subject = new Subject(); ////Registering the observers-DB Users //subject.Register(myObserver1); //subject.Register(myObserver2); //subject.Register(myObserver3); //await context.Response.WriteAsync("Updating Flag = 5 \n"); //subject.Flag = 5; ////Unregistering an observer(DB Subscriber 1)) //subject.Unregister(myObserver1); ////No notification this time DB Subscriber 1. Since it is unregistered. //await context.Response.WriteAsync("\nUpdating Flag = 50 \n"); //subject.Flag = 50; ////DB Subscriber 1 is registering himself again //subject.Register(myObserver1); //await context.Response.WriteAsync("\nUpdating Flag = 100 \n"); //subject.Flag = 100; #endregion #region Comment all except this region to check strategy Pattern Demo & Include StrategyPattern namaspace only //await context.Response.WriteAsync("***Strategy Design Pattern Demo***\n"); //IChoice ic = null; //Context cxt = new Context(); ////For simplicity, we are considering 2 user inputs only. //for (int i = 1; i <= 2; i++) //{ // await context.Response.WriteAsync("\n======================================\n"); // await context.Response.WriteAsync("\nEnter ur choice(1 or 2)"); // await context.Response.WriteAsync(string.Format("\nUser Enters {0}\n",i)); // string c = i.ToString(); // if (c.Equals("1")) // { // ic = new FirstChoice(); // await context.Response.WriteAsync("\nFirstChoice object selected\n"); // } // else // { // ic = new SecondChoice(); // await context.Response.WriteAsync("\nSecondChoice object selected\n"); // } // cxt.SetChoice(ic); // await context.Response.WriteAsync("\nContext set with User seleted Choice object\n"); // cxt.ShowChoice(); //} #endregion #region Comment all except this region to check Adapter Pattern Demo & Include AdapterPattern namaspace only //await context.Response.WriteAsync("***Adapter Design Pattern Demo***\n"); ////CalculatorAdapter cal = new CalculatorAdapter(); //Rect r = new Rect(20, 10); //await context.Response.WriteAsync(string.Format("\nArea of Rectangle is :{0} Square unit",r.CalculateAreaOfRectangle())); //Triangle t = new Triangle(20, 10); //await context.Response.WriteAsync(string.Format("\nArea of Triangle without Adapter is :{0} Square unit", t.CalculateAreaOfTriangle())); //IRect adapter = new TriangleAdapter(t); ////Passing a Triangle instead of a Rectangle //await context.Response.WriteAsync(string.Format("\nArea of Triangle with Triangle Adapter is :{0} Square unit", GetArea(adapter))); ///*GetArea(IRect r) method does not know that through TriangleAdapter, it is getting a Triangle instead of a Rectangle*/ //static double GetArea(IRect r) //{ // r.AboutRectangle(); // return r.CalculateAreaOfRectangle(); //} #endregion #region Comment all except this region to check Bridge Pattern Demo & Include BridgePattern namaspace only //await context.Response.WriteAsync("***Bridge Design Pattern Demo***\n"); //await context.Response.WriteAsync("\nDealing with a Television:"); ////ElectronicGoods eItem = new Television(presentState); //IState presentState = new OnState(); //ElectronicGoods eItem = new Television(); //eItem.State = presentState; //eItem.MoveToCurrentState(); ////Verifying Off state of the Television now //presentState = new OffState(); //eItem.State = presentState; //eItem.MoveToCurrentState(); //await context.Response.WriteAsync("==========================================\n"); //await context.Response.WriteAsync("\n\nDealing with a DVD:"); //presentState = new OnState(); //eItem = new DVD(); //eItem.State = presentState; //eItem.MoveToCurrentState(); //presentState = new OffState(); //eItem.State = presentState; //eItem.MoveToCurrentState(); #endregion #region Comment all except this region to check Builder Pattern Demo & Include BuilderPattern namaspace only //await context.Response.WriteAsync("***Builder Design Pattern Demo***\n"); //Director director = new Director(); //IBuilder carBuilder = new Car("Ford"); //IBuilder motorCycleBuilder = new MotorCycle("Honda"); //// Making Car //director.Construct(carBuilder); //Product carProduct = carBuilder.GetVehicle(); //carProduct.Show(); ////Making MotorCycle //director.Construct(motorCycleBuilder); //Product motorCycleProduct = motorCycleBuilder.GetVehicle(); //motorCycleProduct.Show(); #endregion #region Comment all except this region to check Prototype Pattern Demo & Include PrototypePattern namaspace only await context.Response.WriteAsync("***Prototype Design Pattern Demo***\n"); await context.Response.WriteAsync("************************************\n"); //Base or Original Copy BasicCar nano_base = new Nano("Red Nano") { Price = 100000 }; BasicCar ford_base = new Ford("Blue Ford") { Price = 500000 }; BasicCar bc1; //Nano bc1 = nano_base.Clone(); bc1.Price = nano_base.Price + BasicCar.SetPrice(); await context.Response.WriteAsync(string.Format("\nCar is: {0}, and it's price is Rs. {1} ", bc1.ModelName, bc1.Price)); //Ford bc1 = ford_base.Clone(); bc1.Price = ford_base.Price + BasicCar.SetPrice(); await context.Response.WriteAsync(string.Format("\nCar is: {0}, and it's price is Rs. {1}", bc1.ModelName, bc1.Price)); #endregion await context.Response.WriteAsync("\n"); }); }); }