Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace InterviewPreparation
- {
- class Solution
- {
- public interface IForward
- {
- void GoForward();
- }
- public interface IBackward
- {
- void GoBackward();
- }
- public interface ICar : IForward, IBackward
- {
- }
- public class Car : ICar
- {
- public void GoBackward() { }
- public void GoForward() { }
- public virtual void OpenDoor()
- {
- Console.WriteLine("Open car door");
- }
- }
- public class Motor : IForward
- {
- public void GoForward() { }
- }
- static void Main(string[] args)
- {
- List<IForward> cars = new List<IForward>();
- cars.Add(new Car());
- cars.Add(new Car());
- cars.Add(new Motor());
- // Liskov subsitution: the "car" in the loop can even be a motor now,
- // because we handle it through abstraction
- foreach (IForward car in cars)
- {
- car.GoForward();
- }
- // ------------------------------------------------
- List<int> aList = new List<int> { 1, 2, 3 };
- IEnumerable<int> filtered = Enumerable.Empty<int>();
- try
- {
- // These 2 are the same:
- filtered = Enumerable.Where<int>(aList, a => throw new Exception());
- filtered = aList.Where(a => throw new Exception());
- }
- catch (Exception)
- {
- Console.WriteLine("Catched");
- }
- // Throws an exception because here the predicate gets executed.
- List<int> bList = filtered.ToList();
- }
- // Polimorphism: overloading
- public static void LezDuit() { }
- public static void LezDuit(int a) { }
- // Polimorphism: overriding
- public class RedCar : Car
- {
- public override void OpenDoor()
- {
- base.OpenDoor();
- }
- }
- // ------------------------------------------------
- public class ComputerFactory
- {
- public void CreateComputer()
- {
- //var monitor = new LEDMonitor();
- var monitor = new KatodsugarcsovesMonitor();
- var keyboard = new MechanicalKeyboard();
- var pc = new Windows98Machine(monitor, keyboard);
- }
- }
- public class Windows98Machine
- {
- private MechanicalKeyboard m_Keyboard;
- private IMonitor m_Monitor;
- // Dependency inversion: The dependency is injected, and it is changed to abstraction
- public Windows98Machine(IMonitor monitor, MechanicalKeyboard keyboard)
- {
- m_Monitor = monitor;
- m_Keyboard = keyboard;
- // Tightly coupled dependency --------
- //m_Monitor = new Monitor();
- //m_Keyboard = new MechanicalKeyboard();
- }
- }
- public class MechanicalKeyboard { }
- public class LEDMonitor : IMonitor { }
- public class KatodsugarcsovesMonitor : IMonitor { }
- public interface IMonitor { }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement