Exemplo n.º 1
0
        public void FirstTest()
        {
            ContinentFactory africa = new AfricaFactory();
            var world = new AnimalWorld(africa);
            world.RunFoodChain();

            ContinentFactory america = new AmericaFactory();
            world = new AnimalWorld(america);
            world.RunFoodChain();
        }
Exemplo n.º 2
0
        public AbstractFactoryPattern()
        {
            var asia  = new AsianFactory();
            var world = new AnimalWorld(asia);

            world.RunFoodChain();

            Console.WriteLine("");

            var africa = new AfricanFactory();

            world = new AnimalWorld(africa);
            world.RunFoodChain();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        public void Run()
        {
            // Create and run the African animal world
            var africa = new AfricaFactory();
            var world  = new AnimalWorld(africa);

            world.RunFoodChain();

            // Create and run the American animal world
            var america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();
        }
Exemplo n.º 4
0
        static void RunAbstractFactoryRealWorld()
        {
            // Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);

            world.RunFoodChain();

            // Create and run the American animal world
            ContinentFactory america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();
        }
Exemplo n.º 5
0
        public void TestCreateAndRunAnimal()
        {
            // Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);

            world.RunFoodChain();

            // Create and run the American animal world
            ContinentFactory america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            ContinentFactory africa      = new AfricaFactory();
            AnimalWorld      animalWorld = new AnimalWorld(africa);

            animalWorld.RunFoodChain();

            ContinentFactory america = new AmericaFactory();

            animalWorld = new AnimalWorld(america);
            animalWorld.RunFoodChain();


            Console.ReadKey();
        }
        public void MainTest()
        {
            // TODO
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);

            world.RunFoodChain();

            ContinentFactory america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();

            Assert.AreEqual(1, 1);
        }
Exemplo n.º 8
0
        private static void TestFactory()
        {
            Console.WriteLine("Testing factory...");
            // Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();
            var world = new AnimalWorld(africa);

            world.RunFoodChain();

            // Create and run the American animal world
            ContinentFactory america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            //Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld world = new AnimalWorld(africa);
            world.RunFoodChain();

            // Create and run the American animal world
            ContinentFactory amercia = new AmericaFactory();
            world = new AnimalWorld(amercia);
            world.RunFoodChain();

            //wait for user input before closing application
            Console.ReadKey(true);
        }
Exemplo n.º 10
0
    // Entry point into console application.
    public static void Main()
    {
        // Create and run the African animal world
        continent = new AfricaFactory();
        fauna     = new AnimalWorld(continent);
        fauna.RunFoodChain();

        // Create and run the American animal world
        continent = new AmericaFactory();
        fauna     = new AnimalWorld(continent);
        fauna.RunFoodChain();

        // Wait for user input
        Console.ReadKey();
    }
Exemplo n.º 11
0
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        public static void Main()
        {
            // Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);

            world.RunFoodChain();

            // Create and run the American animal world
            ContinentFactory america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();

            // Wait for user input
            Console.ReadKey();
        }
        public static void Main(string[] args)
        {
            ForegroundColor = ConsoleColor.Cyan;
            const string dateTimeFormat = @"MM / dd / yyyy HH: mm: ss.fff";

            var len = 2;
            var d = 9;
            WriteLine($"{(((len%9)*(d%9))%9)}");


            WriteLine("Start -> {0}\n", DateTime.Now.ToString(dateTimeFormat, CultureInfo.InvariantCulture));

            var africaAnimals = new AnimalWorld<AfricanAminals>();
            africaAnimals.RunFoodChain();

            var americalAnimals = new AnimalWorld<AmericanAnimals>();
            americalAnimals.RunFoodChain();

            WriteLine("\nEnd -> {0}", DateTime.Now.ToString(dateTimeFormat, CultureInfo.InvariantCulture));
            WriteLine("\n\nPress any key ....");
            ReadKey();
        }
Exemplo n.º 13
0
        //Real-world
        public static void AbstractFactoryRealWorld()
        {
            // Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();

            Log.WriteLine("{0} has Created", africa.GetType().Name);
            var world = new AnimalWorld(africa);

            Log.WriteLine("{0} has Created", world.GetType().Name);
            Log.WriteLine("Animal World Create Herbivore and Carnivore");
            Log.WriteLine("Animal World Run Food Chain");
            world.RunFoodChain();

            Log.AddSeparator(5);
            // Create and run the American animal world
            ContinentFactory america = new AmericaFactory();

            Log.WriteLine("{0} has Created", america.GetType().Name);
            world = new AnimalWorld(america);
            Log.WriteLine("{0} has Created", world.GetType().Name);
            Log.WriteLine("Animal World Create Herbivore and Carnivore");
            Log.WriteLine("Animal World Run Food Chain");
            world.RunFoodChain();
        }
        public void AbstractFactory_Works()
        {
            // arrange
            var outputWriter = new OutputWriter();
            AutoFacInstance.Container = base.GetAutoFacContainer(outputWriter);
            
            // Create and run the African animal world
            var africa = new AfricaFactory();
            var africanWorld = new AnimalWorld(africa);
            
            // Create and run the American animal world
            var america = new AmericaFactory();
            var americanWorld = new AnimalWorld(america);

            // act
            africanWorld.RunFoodChain();
            americanWorld.RunFoodChain();

            // assert
            Assert.AreEqual(outputWriter.Outputs.Count, 2);
            Assert.IsNotNull(outputWriter.Outputs);
            Assert.IsNotNull(outputWriter.Outputs.Find(x => x == "Lion eats Wildebeest"));
            Assert.IsNotNull(outputWriter.Outputs.Find(x => x == "Wolf eats Bison"));
        }
    // Entry point into console application.
    public static void Main()
    {
        // Create and run the African animal world
        continent = new AfricaFactory();
        fauna = new AnimalWorld(continent);
        fauna.RunFoodChain();

        // Create and run the American animal world
        continent = new AmericaFactory();
        fauna = new AnimalWorld(continent);
        fauna.RunFoodChain();

        // Wait for user input
        Console.ReadKey();
    }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            #region Design Patterns
            #region Decorator Pattern Example
            Espresso beverage1 = new Espresso();
            Console.WriteLine("Double Mocha Esspresso");
            Mocha d1 = new Mocha(beverage1);
            Mocha d2 = new Mocha(d1);
            Console.WriteLine(d2.Cost() + " " + d2.Description);

            Console.WriteLine("\n House Blend, Moch, Whip");
            HouseBlend beverage2 = new HouseBlend();
            Mocha      d3        = new Mocha(beverage2);
            Whip       d4        = new Whip(d3);
            Console.WriteLine(d4.Cost() + " " + d4.Description);
            #endregion

            #region Factory Pattern
            // Note: constructors call Factory Method
            Document[] documents = new Document[2];

            documents[0] = new Resume();
            documents[1] = new Report();

            // Display document pages
            foreach (Document document in documents)
            {
                Console.WriteLine("\n" + document.GetType().Name + "--");
                foreach (Page page in document.Pages)
                {
                    Console.WriteLine(" " + page.GetType().Name);
                }
            }
            #endregion

            #region Abstract Factory Pattern
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);
            world.RunFoodChain();

            ContinentFactory america = new AmericaFactory();
            world = new AnimalWorld(america);
            world.RunFoodChain();
            #endregion

            #region Singleton
            Console.WriteLine(Singleton.Math.Instance.add(34, 3));
            #endregion

            #region Obsever Pattern
            BaggageHandler  provider  = new BaggageHandler();
            ArrivalsMonitor observer1 = new ArrivalsMonitor("BaggageClaimMonitor1");
            ArrivalsMonitor observer2 = new ArrivalsMonitor("SecurityExit");

            provider.BaggageStatus(712, "Detroit", 3);
            observer1.Subscribe(provider);
            provider.BaggageStatus(712, "Kalamazoo", 3);
            provider.BaggageStatus(400, "New York-Kennedy", 1);
            provider.BaggageStatus(712, "Detroit", 3);
            observer2.Subscribe(provider);
            provider.BaggageStatus(511, "San Francisco", 2);
            provider.BaggageStatus(712);
            observer2.Unsubscribe();
            provider.BaggageStatus(400);
            provider.LastBaggageClaimed();
            #endregion

            #region Strategy Pattern
            SortedList studentRecords = new SortedList();
            studentRecords.Add("samual");
            studentRecords.Add("Jimmy");
            studentRecords.Add("Sandra");
            studentRecords.Add("Vivek");
            studentRecords.Add("Anna");

            studentRecords.SetSortStrategy(new QuickSort());
            studentRecords.Sort();

            studentRecords.SetSortStrategy(new ShellSort());
            studentRecords.Sort();

            studentRecords.SetSortStrategy(new MergeSort());
            studentRecords.Sort();
            #endregion

            #region Composite Pattern
            CompositeElement root = new CompositeElement("Picture");
            root.Add(new PrimitiveElement("Red Line"));
            root.Add(new PrimitiveElement("Blue Circle"));
            root.Add(new PrimitiveElement("Green Box"));

            CompositeElement comp = new CompositeElement("Two Circles");
            comp.Add(new PrimitiveElement("Black Circle"));
            comp.Add(new PrimitiveElement("White Circle"));
            root.Add(comp);

            PrimitiveElement pe = new PrimitiveElement("Yellow Line");
            root.Add(pe);
            root.Remove(pe);

            root.Display(1);
            #endregion

            #region Command Pattern
            User user = new User();

            user.Compute('+', 100);
            user.Compute('-', 50);
            user.Compute('*', 10);
            user.Compute('/', 2);

            user.Undo(4);
            user.Redo(3);
            #endregion

            #region COR (Chain of Responsibility)
            // Setup Chain of Responsibility
            Handler h1 = new ConcreteHandlerA();
            Handler h2 = new ConcreteHandlerB();
            Handler h3 = new ConcreteHandlerC();
            h2.SetSuccessor(h3);
            h1.SetSuccessor(h2);


            // Generate and process request
            int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };

            foreach (int request in requests)
            {
                h1.HandleRequest(request);
            }
            #endregion

            #endregion

            #region AD

            #region List
            MyArrayList list = new MyArrayList(5);
            //setting values
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
            list.add(5);

            Console.WriteLine(list.get(2) + " staat op positie 2");
            //testing print function
            list.print();
            //testing set function
            list.set(2, 10); //true
            list.print();
            list.set(10, 2); //false
            //occurences test
            list.set(0, 2);
            list.set(4, 2);
            list.countOccurences(2);
            //testing clear
            list.clear();
            list.print();

            MyLinkedList <int> linkedList = new MyLinkedList <int>();
            linkedList.addFirst(1);
            linkedList.addFirst(12);
            linkedList.addFirst(3);
            linkedList.addFirst(4);
            linkedList.addFirst(5);
            linkedList.insert(0, 123);
            linkedList.remove(12);
            MyLinkedList <int> .printList(linkedList);

            Console.ReadLine();
            #endregion

            #region Graph
            Graph g = new Graph();

            try
            {
                StreamReader d = new StreamReader(Console.ReadLine());
                string       line;
                while ((line = d.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                    string[] words = line.Split(' ');
                    try
                    {
                        if (words.Length > 3)
                        {
                            Console.WriteLine("Skipping bad line: " + line);
                            continue;
                        }
                        string source = words[0];
                        string dest   = words[1];
                        int    cost   = Int32.Parse(words[2]);

                        g.addEdge(source, dest, cost);
                    }
                    catch (FormatException e)
                    {
                        Console.WriteLine("Skipping bad line: " + line);
                        Console.WriteLine(e);
                    }
                }
            }
            catch (Exception e) { Console.WriteLine(e); }


            //while (processRequest(g));
            #endregion

            #region Binairy tree
            string seperator = "-----------------------------------------------------------------------";
            Console.WriteLine(seperator);
            Console.WriteLine("Binary Tree Basic: ");
            BinaryNode <int> NodeA = new BinaryNode <int>(2);
            BinaryNode <int> NodeB = new BinaryNode <int>(5);
            BinaryNode <int> NodeC = new BinaryNode <int>(6);
            BinaryNode <int> NodeD = new BinaryNode <int>(3);
            BinaryNode <int> NodeE = new BinaryNode <int>(7);
            BinaryNode <int> NodeF = new BinaryNode <int>(10);
            BinaryNode <int> NodeG = new BinaryNode <int>(1);

            NodeE.setRight(NodeG);

            NodeA.setLeft(NodeC);
            NodeA.setRight(NodeD);

            NodeB.setLeft(NodeE);
            NodeB.setRight(NodeF);


            BinaryTree <int> tree = new BinaryTree <int>(12);
            tree.Root.setLeft(NodeA);
            tree.Root.setRight(NodeB);

            tree.printPreOrder();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Binary Search Tree: ");
            BinaryTree <int> BST = new BinaryTree <int>();
            BST.Insert(5);
            BST.Insert(1254);
            BST.Insert(252);
            BST.Insert(378);
            BST.Insert(45);

            BST.Insert(668);
            BST.Insert(71);
            BST.Insert(8);
            BST.Insert(942);
            //fail test
            BST.Insert(1);

            Console.WriteLine(seperator);
            Console.WriteLine("Printing in order: ");
            BST.printInOrder();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Finding Min:");
            Console.WriteLine(BST.FindMin());
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Finding Max: ");
            Console.WriteLine(BST.FindMax());
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Finding value 5:");
            Console.WriteLine(BST.Find(5));
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Removing 5");
            BST.Remove(5);
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Printing in order: ");
            BST.printInOrder();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Removing Min");
            BST.RemoveMin();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Printing in order: ");
            BST.printInOrder();
            Console.ReadLine();
            #endregion

            #region Max heap
            MaxHeap theHeap = new MaxHeap(21);
            theHeap.Insert(40);
            theHeap.Insert(70);
            theHeap.Insert(20);
            theHeap.Insert(60);
            theHeap.Insert(50);
            theHeap.Insert(100);
            theHeap.Insert(82);
            theHeap.Insert(35);
            theHeap.Insert(90);
            theHeap.Insert(10);
            theHeap.DisplayHeap();

            Console.WriteLine("Inserting a new node with value 120");
            theHeap.Insert(120);
            theHeap.DisplayHeap();

            Console.WriteLine("Removing max element");
            theHeap.Remove();
            theHeap.DisplayHeap();

            Console.WriteLine("Changing root to 130");
            theHeap.HeapIncreaseDecreaseKey(0, 130);
            theHeap.DisplayHeap();

            Console.WriteLine("Changing root to 5");
            theHeap.HeapIncreaseDecreaseKey(0, 5);
            theHeap.DisplayHeap();
            Console.ReadLine();
            #endregion

            #region Min heap
            int[] arrA = { 50, 2, 30, 7, 40, 4, 10, 16, 12 };
            Console.WriteLine("Original Array : ");
            for (int i = 0; i < arrA.Length; i++)
            {
                Console.Write("  " + arrA[i]);
            }
            MinHeap m = new MinHeap(arrA.Length);
            Console.WriteLine("\nMin-Heap : ");
            m.createHeap(arrA);
            m.display();
            Console.WriteLine("Extract Min :");
            for (int i = 0; i < arrA.Length; i++)
            {
                Console.Write("  " + m.extractMin());
            }
            #endregion

            #region Sorting
            Console.WriteLine();
            int[] tmpArray = { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41 };
            Console.WriteLine(seperator);
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            var watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.ShellSort(tmpArray);
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Shell sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();

            tmpArray = new[] { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41 };
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);

            watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.PerformInsertionSort(tmpArray);
            watch.Stop();
            elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Insertion sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();

            tmpArray = new[] { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41 };
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);

            watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.MergeSort(tmpArray);
            watch.Stop();
            elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Merge sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();

            tmpArray = new[] { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41, 46 };
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);

            watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.QuickSort(tmpArray, 0, tmpArray.Length - 1);
            watch.Stop();
            elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Quick sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();
            #endregion
            #endregion
            Console.ReadKey();
        }
Exemplo n.º 17
0
  public static void Main( string[] args )
  {
    // Create and run the Africa animal world
    ContinentFactory africa = new AfricaFactory();
    AnimalWorld world = new AnimalWorld( africa );
    world.RunFoodChain();

    // Create and run the America animal world
    ContinentFactory america = new AmericaFactory();
    world = new AnimalWorld( america );
    world.RunFoodChain();

    Console.Read();
  }
Exemplo n.º 18
0
        private static void Main(string[] args)
        {
            //AbstractFactory
            //Provide an interface for creating related objects without specifying their concrete classes.

            AfricaFactory africa = new AfricaFactory();
            AnimalWorld   world  = new AnimalWorld(africa);

            world.RunFoodChain();

            AmericaFactory america = new AmericaFactory();

            world = new AnimalWorld(america);
            world.RunFoodChain();

            Console.WriteLine("\n");

            //=============================================================================================================================================================

            //Singleton
            //Ensure a class has only one instance and provide a global point of access to it.

            Singleton fromPrincipal = Singleton.GetInstance;

            fromPrincipal.PrintDetails("From Principal");
            Singleton fromTeachaer = Singleton.GetInstance;

            fromTeachaer.PrintDetails("From Teacher");
            Singleton fromStudent = Singleton.GetInstance;

            fromStudent.PrintDetails("From Student");

            Singleton oSingleton_1 = new Singleton();
            Singleton oSingleton_2 = new Singleton();

            Console.WriteLine("\n");

            //=============================================================================================================================================================

            //ProtoType
            //The intent behind the usage of a Prototype pattern is for creation of an object clone;
            //in other words it allows us to create a new instance by copying existing instances.

            var dev = new Developer
            {
                FirstName = "Gary",
                Lastname  = "Woodfine",
                Skills    = new List <string> {
                    "C#", "PHP", "SQL", "JavaScript"
                }
            };

            var dev2 = dev.Clone() as Developer;

            Console.WriteLine($"The Cloned  Developer name is { dev2.FirstName }  { dev2.Lastname }");

            Console.WriteLine("The second developer has the following skills: ");

            foreach (var skill in dev2.Skills)
            {
                Console.WriteLine(skill);
            }

            Console.WriteLine("\n");

            //=============================================================================================================================================================

            // Facade
            //Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

            Order order = new Order();

            order.PlaceOrder();

            Console.WriteLine("\n");

            //==============================================================================================================================================================

            // Builder
            //Builder is a creational design pattern that lets you construct complex objects step by step.

            Beverage         beverage;
            BeverageDirector beverageDirector = new BeverageDirector();

            TeaBuider tea = new TeaBuider();

            beverage = beverageDirector.MakeBeverage(tea);
            Console.WriteLine(beverage.ShowBeverage());

            CoffeeBuilder coffee = new CoffeeBuilder();

            beverage = beverageDirector.MakeBeverage(coffee);
            Console.WriteLine(beverage.ShowBeverage());
            Console.Read();
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            //Abstract factory pattern

            ContinentFactory factory = new LahoreFactory();
            AnimalWorld      world   = new AnimalWorld(factory);

            world.RunFoodChain();

            // decoratoer pattern
            BakeryShop.OrderCakeWithCreamCherryScent();
            BakeryShop.OrderPastryWithCream();
            AdapterTestDrive.AdapterTest();

            //When using Dependency Injection, objects are given their dependencies on run time
            //rather than compile time.In other words objects
            //are configured by an external entity.

            // ninjet DI
            var kernel = new StandardKernel();

            kernel.Load(Assembly.GetExecutingAssembly());
            var wap = kernel.Get <IWeapon>();

            wap.sord();

            //castle windsor DI
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());
            var root = container.Resolve <IWeapon>();

            root.sord();

            //simple DI
            //      OperationEvent objOperationEvent = new OperationEvent(new FileLogger());
            //      objOperationEvent.Division();
            //       Console.Read();
            // static constructor behivour.
            var iii = StaticConstructor.a;

            // polymarphism behivour......
            BaseClass  aa = new ChildClass("waqar");
            ChildClass bb = new ChildClass();

            aa.overrideMethod();
            aa.newMethod();
            bb.newMethod();
            aa.virtualwithoutoverride();

            // abstract class behivour;
            childAbstract aClass = new childAbstract();

            aClass.withoutAbstract();
            aClass.withAbstractMethod();

            GetSecondHeightNumber(new int[] { 5, 11, 12, 16, 54, 54, 55, 99, 55, 22, 98, 98, 99, 99, 99, 88, 10, 15 });
            SimpleBubbleSort(new int[] { 3, 60, 35, 2, 45, 320, 5 });

            int[]    arr = { 10, 64, 7, 52, 32, 18, 2, 48 };
            HeapSort hs  = new HeapSort();

            hs.PerformHeapSort(arr);


            Console.ReadKey();

            //Encapsulation
            // List<string> list = new List<string>();
            // list.Sort(); /* Here, which sorting algorithm is used and hows its
            // implemented is not useful to the user who wants to perform sort, that's
            // why its hidden from the user of list. */

            //Abstraction: Is a way of providing generalization and hence a common way
            //to work with objects of vast diversity. e.g.
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            #region Creational
            #region Abstract Factory Design Pattern.
            // Create and run the African animal world
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);
            world.RunFoodChain();

            // Create and run the American animal world
            ContinentFactory america = new AmericaFactory();
            world = new AnimalWorld(america);
            world.RunFoodChain();
            #endregion

            #region  Builder Design Pattern.
            //VehicleBuilder builder;
            //// Create shop with vehicle builders
            //Shop shop = new Shop();

            //// Construct and display vehicles
            //builder = new ScooterBuilder();
            //shop.Construct(builder);
            //builder.Vehicle.Show();

            //builder = new CarBuilder();
            //shop.Construct(builder);
            //builder.Vehicle.Show();

            //builder = new MotorCycleBuilder();
            //shop.Construct(builder);
            //builder.Vehicle.Show();
            #endregion

            #region Factory Method Design Pattern.
            //Document[] documents = new Document[2];

            //documents[0] = new Resume();
            //documents[1] = new Report();

            //// Display document pages

            //foreach (Document document in documents)
            //{
            //    Console.WriteLine("\n" + document.GetType().Name + "--");
            //    foreach (Page page in document.Pages)
            //    {
            //        Console.WriteLine(" " + page.GetType().Name);
            //    }
            //}
            #endregion

            #region Prototype Design Pattern
            //ColorManager colormanager = new ColorManager();
            //// Initialize with standard colors

            //colormanager["red"] = new Color(255, 0, 0);
            //colormanager["green"] = new Color(0, 255, 0);
            //colormanager["blue"] = new Color(0, 0, 255);

            //// User adds personalized colors

            //colormanager["angry"] = new Color(255, 54, 0);
            //colormanager["peace"] = new Color(128, 211, 128);
            //colormanager["flame"] = new Color(211, 34, 20);

            //// User clones selected colors

            //Color color1 = colormanager["red"].Clone() as Color;
            //Color color2 = colormanager["peace"].Clone() as Color;
            //Color color3 = colormanager["flame"].Clone() as Color;
            #endregion

            #region Singletone
            //LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
            //LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
            //LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
            //LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

            //// Same instance?

            //if (b1 == b2 && b2 == b3 && b3 == b4)
            //{
            //    Console.WriteLine("Same instance\n");
            //}

            //// Load balance 15 server requests

            //LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
            //for (int i = 0; i < 15; i++)
            //{
            //    string server = balancer.Server;
            //    Console.WriteLine("Dispatch Request to: " + server);
            //}
            #endregion
            #endregion

            #region Structural
            #region Adapter
            //// Non - adapted chemical compound
            //Compound unknown = new Compound("Unknown");
            //unknown.Display();

            //// Adapted chemical compounds
            //Compound water = new RichCompound("Water");
            //water.Display();

            //Compound benzene = new RichCompound("Benzene");
            //benzene.Display();

            //Compound ethanol = new RichCompound("Ethanol");
            //ethanol.Display();
            #endregion

            #region Bridge
            //// Create RefinedAbstraction
            //Customers customers = new Customers("Chicago");

            //// Set ConcreteImplementor
            //customers.Data = new CustomersData();

            //// Exercise the bridge
            //customers.Show();
            //customers.Next();
            //customers.Show();
            //customers.Next();
            //customers.Show();
            //customers.Add("Henry Velasquez");

            //customers.ShowAll();
            #endregion

            #region Composite
            //// Create a tree structure
            //CompositeElement root = new CompositeElement("Picture");
            //root.Add(new PrimitiveElement("Red Line"));
            //root.Add(new PrimitiveElement("Blue Circle"));
            //root.Add(new PrimitiveElement("Green Box"));

            //// Create a branch
            //CompositeElement comp = new CompositeElement("Two Circles");
            //comp.Add(new PrimitiveElement("Black Circle"));
            //comp.Add(new PrimitiveElement("White Circle"));
            //root.Add(comp);

            //// Add and remove a PrimitiveElement
            //PrimitiveElement pe = new PrimitiveElement("Yellow Line");
            //root.Add(pe);
            //root.Remove(pe);

            //// Recursively display nodes
            //root.Display(1);
            #endregion

            #region Decorator
            //// Create book
            //Book book = new Book("Worley", "Inside ASP.NET", 10);
            //book.Display();

            //// Create video
            //Video video = new Video("Spielberg", "Jaws", 23, 92);
            //video.Display();

            //// Make video borrowable, then borrow and display
            //Console.WriteLine("\nMaking video borrowable:");

            //Borrowable borrowvideo = new Borrowable(video);
            //borrowvideo.BorrowItem("Customer #1");
            //borrowvideo.BorrowItem("Customer #2");

            //borrowvideo.Display();
            #endregion

            #region Facade
            //// Facade
            //Mortgage mortgage = new Mortgage();
            //// Evaluate mortgage eligibility for customer
            //Customer customer = new Customer("Ann McKinsey");
            //bool eligible = mortgage.IsEligible(customer, 125000);
            //Console.WriteLine("\n" + customer.Name + " has been " + (eligible ? "Approved" : "Rejected"));
            #endregion

            #region Flyweight
            //// Build a document with text
            //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);
            //}
            #endregion

            #region Proxy
            //// Create math proxy
            //MathProxy proxy = new MathProxy();

            //// Do the math
            //Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
            //Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
            //Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
            //Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
            #endregion
            #endregion

            #region Behavioral
            #region Chain of Responsibility
            //// Setup Chain of Responsibility
            //Approver larry = new Director();
            //Approver sam = new VicePresident();
            //Approver tammy = new President();

            //larry.SetSuccessor(sam);
            //sam.SetSuccessor(tammy);

            //// Generate and process purchase requests

            //Purchase p = new Purchase(2034, 350.00, "Assets");
            //larry.ProcessRequest(p);

            //p = new Purchase(2035, 32590.10, "Project X");
            //larry.ProcessRequest(p);

            //p = new Purchase(2036, 122100.00, "Project Y");
            //larry.ProcessRequest(p);
            #endregion

            #region Command
            ////// Create user and let her compute
            //User user = new User();

            //// User presses calculator buttons
            //user.Compute('+', 100);
            //user.Compute('-', 50);
            //user.Compute('*', 10);
            //user.Compute('/', 2);

            //// Undo 4 commands
            //user.Undo(4);

            //// Redo 3 commands
            //user.Redo(3);
            #endregion

            #region 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);
            #endregion

            #region Iterator
            //// Build a collection
            //Collection collection = new Collection();
            //collection[0] = new Item("Item 0");
            //collection[1] = new Item("Item 1");
            //collection[2] = new Item("Item 2");
            //collection[3] = new Item("Item 3");
            //collection[4] = new Item("Item 4");
            //collection[5] = new Item("Item 5");
            //collection[6] = new Item("Item 6");
            //collection[7] = new Item("Item 7");
            //collection[8] = new Item("Item 8");

            //// Create iterator
            //Iterator iterator = collection.CreateIterator();

            //// Skip every other item
            //iterator.Step = 2;

            //Console.WriteLine("Iterating over collection:");

            //for (Item item = iterator.First();
            //    !iterator.IsDone; item = iterator.Next())
            //{
            //    Console.WriteLine(item.Name);
            //}
            #endregion

            #region Mediator
            //// Create chatroom
            //Chatroom chatroom = new Chatroom();

            //// Create participants and register them
            //Participant George = new Beatle("George");
            //Participant Paul = new Beatle("Paul");
            //Participant Ringo = new Beatle("Ringo");
            //Participant John = new Beatle("John");
            //Participant Yoko = new NonBeatle("Yoko");

            //chatroom.Register(George);
            //chatroom.Register(Paul);
            //chatroom.Register(Ringo);
            //chatroom.Register(John);
            //chatroom.Register(Yoko);

            //// Chatting participants

            //Yoko.Send("John", "Hi John!");
            //Paul.Send("Ringo", "All you need is love");
            //Ringo.Send("George", "My sweet Lord");
            //Paul.Send("John", "Can't buy me love");
            //John.Send("Yoko", "My sweet love");
            #endregion

            #region Memento
            //SalesProspect s = new SalesProspect();
            //s.Name = "Noel van Halen";
            //s.Phone = "(412) 256-0990";
            //s.Budget = 25000.0;

            //// Store internal state

            //ProspectMemory m = new ProspectMemory();
            //m.Memento = s.SaveMemento();

            //// Continue changing originator

            //s.Name = "Leo Welch";
            //s.Phone = "(310) 209-7111";
            //s.Budget = 1000000.0;

            //// Restore saved state
            //s.RestoreMemento(m.Memento);
            #endregion

            #region Observer
            //// Create IBM stock and attach investors
            //IBM ibm = new IBM("IBM", 120.00);
            //ibm.Attach(new Investor("Sorros"));
            //ibm.Attach(new Investor("Berkshire"));

            //// Fluctuating prices will notify investors
            //ibm.Price = 120.10;
            //ibm.Price = 121.00;
            //ibm.Price = 120.50;
            //ibm.Price = 120.75;
            #endregion

            #region State
            //// Open a new account
            //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);
            #endregion

            #region Strategy
            //// Two contexts following different strategies
            //SortedList studentRecords = new SortedList();

            //studentRecords.Add("Samual");
            //studentRecords.Add("Jimmy");
            //studentRecords.Add("Sandra");
            //studentRecords.Add("Vivek");
            //studentRecords.Add("Anna");

            //studentRecords.SetSortStrategy(new QuickSort());
            //studentRecords.Sort();

            //studentRecords.SetSortStrategy(new ShellSort());
            //studentRecords.Sort();

            //studentRecords.SetSortStrategy(new MergeSort());
            //studentRecords.Sort();
            #endregion

            #region Template
            //DataAccessObject daoCategories = new Categories();
            //daoCategories.Run();

            //DataAccessObject daoProducts = new Products();
            //daoProducts.Run();
            #endregion

            #region Visitor
            //// Setup employee collection
            //Employees e = new Employees();
            //e.Attach(new Clerk());
            //e.Attach(new Manager());
            //e.Attach(new ExecuterDirector());

            //// Employees are 'visited'
            //e.Accept(new IncomeVisitor());
            //e.Accept(new VacationVisitor());
            #endregion
            #endregion


            #region UnityOfWork

            /*
             * public class HomeController : Controller
             * {
             *  UnitOfWork unitOfWork;
             *  public HomeController()
             *  {
             *      unitOfWork = new UnitOfWork();
             *  }
             *  public ActionResult Index()
             *  {
             *      var books = unitOfWork.Books.GetAll();
             *      return View();
             *  }
             *
             *  public ActionResult Create()
             *  {
             *      return View();
             *  }
             *
             *  [HttpPost]
             *  public ActionResult Create(Book b)
             *  {
             *      if(ModelState.IsValid)
             *      {
             *          unitOfWork.Books.Create(b);
             *          unitOfWork.Save();
             *          return RedirectToAction("Index");
             *      }
             *      return View(b);
             *  }
             *
             *  public ActionResult Edit(int id)
             *  {
             *      Book b = unitOfWork.Books.Get(id);
             *      if (b == null)
             *          return HttpNotFound();
             *      return View(b);
             *  }
             *
             *  [HttpPost]
             *  public ActionResult Edit(Book b)
             *  {
             *      if (ModelState.IsValid)
             *      {
             *          unitOfWork.Books.Update(b);
             *          unitOfWork.Save();
             *          return RedirectToAction("Index");
             *      }
             *      return View(b);
             *  }
             *
             *  public ActionResult Delete(int id)
             *  {
             *      unitOfWork.Books.Delete(id);
             *      unitOfWork.Save();
             *      return RedirectToAction("Index");
             *  }
             *
             *  protected override void Dispose(bool disposing)
             *  {
             *      unitOfWork.Dispose();
             *      base.Dispose(disposing);
             *  }
             * }
             */
            #endregion
            Console.ReadKey();
        }