Friday, November 2, 2012

Builder Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Previously I discussed
Strategy Pattern
Factory Pattern
Abstract Factory Pattern
Observer Pattern
Facade Pattern

Today I'll be discussing the Builder Pattern. I usually don't include UML because they are all over the web and haven't brought that much extra value to my write-ups. But this pattern has a few more parts then the previous patterns I have dicussed, and I feel it will help.

Straight from Wikipedia











The builder pattern is a creational pattern, and the point of it is to encapsulate the complexities of creating a
complicated object. The Builder pattern can also create variations of the complex object.

At first I thought this pattern sounded familiar. It sounded a little bit like the Factory or Factory Method Pattern or maybe Abstract Factory. Its pretty different though and a short definition of each should help illustrate.

Factory - Client calls factory and factory directly returns one of many different types based on the parameters given to it. The clinet doesn't know what it's getting back only that the object inherits from a given abstract class or interface.
Factory Method - Client has an instance of an abscract factory wich defines an abstract method for creating products, but the client instantiates the factory with a conrete instance of that factory. The concrete instance impliments the create method and can create one of many types of the product but only return the parent class or interface that represents the product.
Abstract Factory - There are some similarities to the Factory method pattern here but just remember the Factory method pattern only returns one parent type to the client. In Abstract Facotry the client has a reference to an abstract factory, and instanciates it with a concreate factory that implements the abstract factory. The concrete factory creates concrete products and returns multiple parent types to the client.

Builder Pattern - An abstract builder class defines abstract methods for creating various parts, and a method for returning a product. Concrete builders implement the abstract builder class and are responcible for building the parts, keeping track of their representations and providing a method to return the final product. A director class provides a construction method that calls the part building methods in the concrete builder classes. (In what ever order or with what ever parameters it decides on).

Below is my car demonstration of the Builder pattern. The source code along with all other pattern examples can be found here

















 

Tuesday, October 30, 2012

Part 2 Entity Framework 5 using the POCO pattern, a data first approach, for a Table Per Hierarchy model

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Part 2: MVC 4 with existing context class, and an abstract base type

Previously in Part 1 I discussed a data first approach to using Entity Framework, existing POCO's, and a table per hierarchy design.

With all that wired up I began to evaluate MVC 4.

Most MVC tutorials will have you start off with a table first approach or an object first approach. In the case of a table first approach you will end up with a datamodel (edmx file), and they will let EF code generate entity classes inheariting from EntityObject and a context class inheariting from ObjectContext. Some tutorials even advise that these entities might be a tad heavy for some uses. The alternative is to use DbContext by right clicking the model and choosing "Add code generation item", and selecting "ADO.NET DbContext Generator". This leaves you with a much more simplified context class inheriting from DbContext that just returns sets of each entity. You also get a much more stripped down simple entity class definitions.

I did not used EF code generation but instead defined my own entities and context class. (This will come into play later).

After adding an MVC app to my solution and choosing Razor as my view engine, I first needed to create a controller. In the "Add Controller" prompt you have the ability to choose a controller template that will wire up read/write actions and views for you. All you need is a model class and a context class.

If you choose this option you end up with a BookStore controller that already has the actions wired up for you.
You also get a class level instance of your context object instantiated in the controller.
Also notice the Get and Post verb comments added, (More about that later).



Also you get all your Razor cshtml views created for you.













This is enough to start the MVC application and view the default layout that comes with it.
Notice the RESTful URL style, and seperate views representing basic CRUD operations.



But there's a small problem. If I go to POST Or GET on one of my resources (create or an edit) I get this big ugly error.

Server Error in '/' Application.

Cannot create an abstract class.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: Cannot create an abstract class.




Why am I getting this? Pretty simple you cannot instantiate an abstract class. MVC has these ModelBinders, and I'm no expert but in simple terms they help bind the model information to the views. The default model binder may realize it needs a Book object but remember that discriminator thing we talked about in Part 1? The default model binder doesn't know how to make this discrimination. But we can define our own ModelBinder. To do that you need to derive from DefaultModelBinder. I'm only going to override the CreateModel method. Here is the result. 



But, we aren't done quite yet. I needed to tell the application to use this new binder before it worked correctly. You do this in global.aspx. 

Now that I have defined my custom modelbinder and added it to the global.aspx I can run the site. Its still just a very out of the box MVC 4 application. Notice the default edit and create views that got made for you. They don't reflect all the properties in our objects.





















My enums are missing. This may be because of how we had to map the entities, but fixing is pretty easy. I added the following lines to use the DropdownListFor control in the html helper



This control requires a SelectedList of values. You can add the C# required to accomplish this directly in your cshtml page using the open and close tags like @{ }

Instead I added a static method to the book class. that looks like so.


Technically putting this functionality in the Book class is all kinds of wrong, and I would not actually do this in  a production application. The reason not to do this is I would be breaking the "separation of concerns" principle by bringing a UI concern into a domain object. This whole demo app could be structured so that my UI layer doesn't even know about my domain objects. A service layer could pass the UI layer nice flat DTO's. I could then add this method to the Book DTO. 

In the end I end up with something that represents all the elements ofthe book object I need to do a create. 





















Obviously this is still not in a state I can really use. No one knows what ReturnPolicy value 3 means. To handle that I can decorate my Enum's with the Componentmodel.DescriptionAttribute and alter my EnumToSelectedList method so that the SelectedListItems text value pulls the description attribute. That's outside the scope of this blog but if I get around to writing it I will edit this blog and add it.

More to come in:

Part 3: MVC 4 view engine, Observer Pattern, and binding


Monday, October 29, 2012

Facade Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Previously I discussed
Strategy Pattern
Factory Pattern
Abstract Factory Pattern
Observer Pattern

The Facade pattern is widely used, and frameworks, and API's  are common implementers of this pattern. Often times a complex API or framework can have interfaces capable of large amounts of functionality and complexity. There may be too much complexity for the intended client to have to deal with. Stringing together a series of function calls for example. This is where the Facade pattern comes in to play. The Facade simply provides a layer of abstraction and or encapsulation by wrapping one or more complex interfaces to provide a unified interface showing only what is necessary to the intended client.

Considerations when implementing a facade layer:
Necessity: Is the facade really unifying complex interfaces for a client that doesn't need to use or understand all the functionality.
Forcing: Is the facade forced on the client? A facade should be bypass-able.
Adding functionality: Is the facade adding functionality? It shouldn't. Its primary focus is to unify a subsystem. It may collect some information to call several methods within the subsystem, therefore unifying functionality, but if functionality is added it might not really be the facade pattern, maybe Decorator instead.

Drawing from the automotive realm again Lets take the ignition process as an example. You the client want to turn the key and have the car start. You don't want to to think about the ignition switch allowing the electrical system to have power from the battery and in turn send electricity to the starter solenoid. The solenoid to send power from the battery to the starting motor. The gear on the starting motor to turn the larger gear on the flywheel. The flywheel to turn the crank driving the pistons. The vacuum from the pistons to pull atomized fuel and air mixture from the carburetor into the cylinders to be ignited by the spark plugs firing inside the cylinders... You just want your start method. You want to call it and let the rest of the stuff behind the scenes happen without your knowledge.

*Note it may be tempting to implement your facade as a singleton. Take a look at this interesting article discussing singleton, GoF patterns, their association with C++, and when is the best time to use a singleton. Its an interesting read. I'm not saying you shouldn't use it but just something of interest.

Here is that ignition example in code. (*Not how I would layout an object model for a serious project relating to an engines ignition process. But, its complex enough to get the point across for this demo).
The entire solution containing this project and the previously discussed projects can be found here.

//Ignition class


//Starter class and solenoid interface. Implements ISolenoidElectronic indicating it is a type of device that //requires a solenoid and should be expected to have a run method. (Not necessary for the Facade pattern //just makes this example make more sense to me.


//Flywheel Class


//Crank


//Carburetor


//Cylinder


//Sparkplug


//Facade class

Wednesday, October 17, 2012

Part 1 Entity Framework 5 using the POCO pattern, a data first approach, for a Table Per Hierarchy model

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Recently I wanted to become more familiar with Entity Framework, and MVC.
I'm going to discuss what I learned in a 3 part blog.

Part 1: TPH, Data First, with existing POCO's
Part 2: MVC 4 with existing context class, and an abstract base type
Part 3: MVC 4 view engine, Observer Pattern, and binding


Part 1: TPH, Data First, with existing POCO's

In the past I have worked with NHibernate, and Telirik Open Access ORM's. I have actually used Entity Framework a few times but in very simple scenarios. I follwed the wizards, and let EF create my entities.

I felt that this was pretty unrealistic experience, so I set out to make myself go through some pain so that I could learn the ORM better.

I decided that in many companies I would be asked to map to already existing data and object models.

I  already had an existing bookstore demo. This demo included an object model and a data schema. The two were not designed with this EF MVC demo in mind. So I thought I should have to jump through a few hoops to make it work. Well I did.

The model consists of one complex type (an abstract base class called book). And three POCO's (derived book types).

Here is the base class.


Here are the POCO's

Here is the very simple Book table.

I know its not a great idea to directly represent an Enum in a table by it's numeric value. But, I had read EF 5 has better Enum support so I wanted to put it to the test.

First I created an ADO.NET Entity Data Model. By default I ended up with something that looked like this:

First thing to do after generating the model was to set the "Code Generation Strategy" to "None". This stops EF from generating entities for you. *Remember I am plannig on using existing classes for my object model. Next I marked the Book entity type as Abstract.

The way the model is set now will work, but I don't like it yet. When I get a book out of my database I want it automatically casted to the derived type it really represents. I.E. I want many different types to map to the same table. This is called a "Table-per-hierarchy" design. There is also a Table-per-Type design but I'm not going to go into the differences. To accomplish the behavior I right clicked in the model's blank area, and chose "Add new Entity..." I'm guessing there is some string magic that goes on here so when typing the names of your derived types be sure to spell them the same way you did in your class declarations.
I created PaperBack, Magazine, and HardCover entities and set their base type to "Book"

The map looks like this now:



Almost done, but I need a way for EF to know how to map the derived types when fetching them from the DB. To do this I used a discriminator. In this case "BookTpye" is my discriminator. Right click on BookType in the Book entity, and choose "Delete from model". Now view the mapping details for the PaperBack entity. Click on "Add a condition", I chose BookType and the equals operator, and set the value to 3. This tells EF when the BookType value is three cast the object to PaperBack. I repeated this for Magazine and HardCover.

After that I mapped the Enum's. There is a new "Convert To Enum" option on the right click menu. It brings up a window that looks like this:





















And unlike earlier versions of EF this Enum mapping actually works.

Because I chose a code generation strategy of none I have no context class. I chose to implement a context class that inherits from ObjectContext. I could have also used dbContext, but I didn't.

The class itself is easy. The hard part came in troubleshooting various issues I had with my entity connection string's metadata. The problems I had there are a little outside the scope of this blog. I don't want to go too far off on a rabbit trail, but there are several great sites for troubleshooting issues of this type.

Here's the context class:

Here is a class that represents a service layer and exposes functionality of the context class.
Later on I could take this service layer and implement a more traditional SOA approach. I could set it up so that my DO's stay on one side of my service, and DTO's go out to my UI layer. I can set up some object validation in my service layer as well.




With these layers set up I can perform all the basic CRUD functions I need to make a sample MVC application.


As long as I was already in VS 2012 I went ahead and used MVC 4.

I will go over that portion in Part2.





Observer Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.

Previously I discussed
Strategy Pattern
Factory Pattern
Abstract Factory Pattern

Due to how events are handled one of the most widely used patterns in the .Net framework is the Observer Pattern.

The main point of the observer pattern is the allow objects to be notify of state change in other objects without being tightly coupled. At least thats how I would describe it to someone in my own words.

A more text book definition is:
"Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically" Got that from OODesigns.

If you ever written an application using the architectural pattern's MVC or MVVM you've used the observer pattern.

As usual I will not go into a lot of detail defining the pattern, there's plenty of sites that have already done that. Below is my example, and here is the source code.

*Note this is a very basic example. I point that out because you can get quite a bit more specific in exactly what flavor of the observer pattern you implement. I believe publish / subscribe is the most widely used. Another is using a feature called an event manager or change manager, or Event Emitter/Target/Dispatcher. My example is a simple publisher / subscriber flavor. Also within that flavor you can implement notifications in a "push" or "pull" manner. Push being the subject always informs the observers of change, and "pull" being the observers can reach out and check for changes in the subject when they want. This example uses the Push technique.

//Subject interface
public interface IEngine
{
      string Name { get; set; }
      List<ISubscriber> Subscribers { get; set; }
      void Notify();
      void Attach(ISubscriber subscriber);
      void Detach(ISubscriber subscriber);
      int EngineTemp { get; set; }
}

//Concrete Subject
public class SilveradoEngine : IEngine
{
        public List<ISubscriber> Subscribers { get; set; }

        public SilveradoEngine()
        {
            Subscribers = new List<ISubscriber>();
        }

        public void Notify()
        {
            foreach(ISubscriber subs in Subscribers)
            {
                subs.Update(this);
            }
        }

        public void Attach(ISubscriber subscriber)
        {
            Subscribers.Add(subscriber);
        }

        public void Detach(ISubscriber subscriber)
        {
            Subscribers.Remove(subscriber);
        }

        private int _EngineTemp;
        public int EngineTemp
        {
            get
            {
                return _EngineTemp;
            }
            set
            {
                _EngineTemp = value;
                Notify();
            }
        }

        public string Name { get; set; }
}

//Observer or subscriber interface
public interface ISubscriber
{
      void Update(SilveradoEngine engine);
}

//Concrete Observer 1
public class EngineTemperatureDashLight : ISubscriber
{
        IEngine engine;
        public EngineTemperatureDashLight()
        {
            this.engine = engine;
        }
        public void Update(SilveradoEngine engine)
        {
            this.engine = engine;
            EngineTempWarningLight = this.engine.EngineTemp > 500 ? true : false;
        }

        public bool EngineTempWarningLight {get; set; }

}

//Concrete Observer 2
public class OnStarAlert : ISubscriber
{
        IEngine engine;
        public OnStarAlert(IEngine engine)
        {
            this.engine = engine;
        }
       
        public void Update(SilveradoEngine engine)
        {
            this.engine = engine;
            OnstartHasAlerts = this.engine.EngineTemp > 500 ? true : false;
        }

        public bool OnstartHasAlerts { get; set; }
}

Wednesday, October 10, 2012

Abstract Factory Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss. 

Previously I discussed the Strategy Pattern and the Factory Pattern. Most recently I've been looking at the Abstract Factory Pattern.

Here's the general definition used throughout the internet:
The abstract factory pattern is considered a creational pattern. In general this pattern is most useful when a client needs to create a family of related or dependent objects without specifying the concrete class.

A common example is a drawing or UI framework. An abstract Factory Pattern might be used to create a family of brushes or a palette of colors.

The client knows about the abstract product, but it doesn't know or care about the the concrete classes created by the methods exposed by the abstract factory.

Abstract factory pattern can be a way to encapsulate concrete factories with commonalities. If the system needs to create multiple families or a library of products without being concerned with implementation details, then this patten can be used.

Here's my example using the vehicle theme again.

//The abstract factory
abstract class AbstractFactory
    {
        public abstract Car CreateCar();
        public abstract Truck CreateTruck();
    }

//The concrete factories implementing the interface defined by the abstract factory
class BaseModelFactory : AbstractFactory
    {
        public override Car CreateCar()
        {
            return new BaseModelCar();
        }
        public override Truck CreateTruck()
        {
            return new BaseModelTruck();
        }
    }

class FullyLoadedFactory : AbstractFactory
    {
        public override Car CreateCar()
        {
            return new FullyLoadedCar();
        }
        public override Truck CreateTruck()
        {
            return new FullyLoadedTruck();
        }
    }

class SportModelFactory : AbstractFactory
    {
        public override Car CreateCar()
        {
            return new SportModelCar();
        }
        public override Truck CreateTruck()
        {
            return new SportTruck();
        }
    }

//Abstract Product 1
abstract class Car
    {
        public abstract Seats Seat { get; }
        public abstract Trims Trim { get; }
        public abstract AccessoriesPackages AccessoriesPackage { get; }
        public abstract Engines Engine { get; }
        public abstract int GetTrunkSpace();
        public abstract string GetTitle();
    }

//Abstract product 2
abstract class Truck
    {
        public abstract Seats Seat { get; }
        public abstract Trims Trim { get; }
        public abstract AccessoriesPackages AccessoriesPackage { get; }
        public abstract Engines Engine { get; }
        public abstract int GetBedSpace();
        public abstract string GetTitle();
    }

//Concrete Products
class BaseModelCar : Car
    {
        public override Seats Seat
        {
            get { return Seats.Cloth; }
        }

        public override Trims Trim
        {
            get { return Trims.Base; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.Base; }
        }

        public override Engines Engine
        {
            get { return Engines.Economy; }
        }

        public override int GetTrunkSpace()
        {
            return 3 * 2;
        }

        public override string GetTitle()
        {
            return "a reliable dependable no frills base model sedan.";
        }
    }

class BaseModelTruck : Truck
    {
        public override Seats Seat
        {
            get { return Seats.Cloth; }
        }

        public override Trims Trim
        {
            get { return Trims.Base; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.Base; }
        }

        public override Engines Engine
        {
            get { return Engines.Economy; }
        }

        public override int GetBedSpace()
        {
            return 8 * 4 * 2;
        }

        public override string GetTitle()
        {
            return "a reliable dependable no frills base model truck.";
        }
    }

class FullyLoadedCar : Car
    {
        public override Seats Seat
        {
            get { return Seats.Leather; }
        }

        public override Trims Trim
        {
            get { return Trims.ChromePackage; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.FullyLoaded; }
        }

        public override Engines Engine
        {
            get { return Engines.Touring; }
        }

        public override int GetTrunkSpace()
        {
            return 4 * 3;
        }

        public override string GetTitle()
        {
            return "a top of the line state of the art fully loaded car.";
        }
    }

class FullyLoadedTruck : Truck
    {
        public override Seats Seat
        {
            get { return Seats.Leather; }
        }

        public override Trims Trim
        {
            get { return Trims.ChromePackage; }
        }

        public override AccessoriesPackages AccessoriesPackage
        {
            get { return AccessoriesPackages.FullyLoaded; }
        }

        public override Engines Engine
        {
            get { return Engines.Touring; }
        }

        public override int GetBedSpace()
        {
            return 6 * 4 * 2;
        }

        public override string GetTitle()
        {
            return "a top of the line state of the art fully loaded truck.";
        }
    }



And it goes on the same for sport car/truck.
*I could have flipped this example and made the abstract product be the package type (Fully loaded, Base Sport). Then I could have let the different vehicle types be the concrete products. In the end my client could have then said show my all the types of trucks, and I could have used the abstract factory to create a truck of type fully loaded, Base, and Sport.

*Note my code implies the use of some enums. I did not show the definition of the enums in the code snippets in this blog, but they are in the source code
.
Here is the source code complete with an example of a client calling the methods exposed by the abstract factory, and listing out the vehicles features.
DesignPatternExamples

Factory Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to constructively discuss.  

Previously I discussed the Strategy Pattern Today I've spent some time looking at the Factory Pattern.
What I've learned is that opposed to the Strategy pattern which is a behavioral pattern the Factory pattern is a creational pattern. So what does that mean? Many times a creational pattern may be used in a framework. But almost always the reason is to help deal with complexities involved in object creation. If there are some choices to be made about what type of object to instantiate, if the object can be represented in a general form then the creational pattern may work well for that situation. From my reading the key principle in the creational pattern is encapsulation. when designing using this pattern you're going to encapsulate knowledge of what concrete class the framework uses, and how they are created.

But I don't just want to regurgitate my readings. Here is the example I put together to help myself understand the pattern better:

(Another car example).

*Note you can use an abstract base class or an interface. I chose an interface this time just because I used an abstract base last time.

//Here is the interface. Simple enough. (Drivetrain being the distinguisher).
 public interface Car
 {
        String Title { get; }
        DriveTrain DriveTrain { get; }
 }

//A couple of concrete types implementing the interface
class ClassicCar : Car
{
      public DriveTrain DriveTrain
      {
          get { return CarFactoryPattern.DriveTrain.TwoByFor; }
      }

      public string Title
      {
          get { return "a great classic"; }
      }
}

class SportsCar : Car
{
      public DriveTrain DriveTrain
      {
          get { return CarFactoryPattern.DriveTrain.AllWheelDrive; }
      }

      public string Title
      {
          get { return "an awesome sports car"; }
      }
}

class SUV : Car
{
      public DriveTrain DriveTrain
      {
          get { return CarFactoryPattern.DriveTrain.FourByFour; }
      }

      public string Title
      {
          get { return "an all purpose utility vehicle"; }
      }
 }

//The factory
public static class Factory
{
      public static Car GetCar(DriveTrain driveTrain)
      {
          switch (driveTrain)
          {
              case DriveTrain.AllWheelDrive:
                  return new SportsCar();
              case DriveTrain.FourByFour:
                  return new SUV();
              case DriveTrain.TwoByFor:
                  return new ClassicCar();
              default:
                  return null;
          }
      }
}

//The client
static void Main(string[] args)
{
          Console.WriteLine("Pick a drivetrain to go in your new car: 1 AWD, 2 4X4, 3 2WD.");
          switch (Console.ReadLine())
          {
              case "1":
                  Console.WriteLine("You will be driving " + Factory.GetCar(DriveTrain.AllWheelDrive).Title);
                  break;
              case "2":
                  Console.WriteLine("You will be driving " + Factory.GetCar(DriveTrain.FourByFour).Title);
                  break;
              case "3":
                  Console.WriteLine("You will be driving " + Factory.GetCar(DriveTrain.TwoByFor).Title);
                  break;
              default:
                  Console.WriteLine("Please make a valid selection.");
                  break;
          }
}

The point is creation of the type is encapsulated. How the types tie together or how they are differentiated is encapsulated. The client just knows it needs a car and that it needs to be of a certain drivetrain type.

The source code can be found here. (VS 2012) Example solution

Monday, October 8, 2012

Strategy Pattern

*Disclaimer these writings are for my own learning purposes not as advice to others. If any part is incorrect please feel free to politely discuss. 

The Strategy Pattern is known as a behavioral pattern.
The keys to achieving the pattern are to encapsulate a family of algorithms, let those algorithms be interchangeable.

Here is my example: (C#)

In this example (Expansion of example used in wikipedia) we will take a car class and implement a family of brake behaviors. Notice the braking functionality is swappable at runtime.
Here's a link to a solution complete with a little console app to see it run.
Strategy Pattern Car example


*Note the dependency injection in this example. Its being achieved through a technique called "Constructor injection". If you have read Martin Fowler's inversion of control writings you have probably seen him talk about how an assembler piece can be responcible for injecting the implementation.
I'm my example my client is my assembler, and it is injecting the brake behavior implementation through constructor injection.


//Interface
  public interface IBrakeBehavior
  {
        bool Brake(int speed, Condition condition, int distance);
  }

//Base class car
   public class Car
    {
        private IBrakeBehavior brakeStrat;
        public Car(IBrakeBehavior brakeStrategy)
        {
            brakeStrat = brakeStrategy;
        }

        public bool ApplyBrakes(int speed, Condition cond, int distance)
        {
            return brakeStrat.Brake(speed, cond, distance);
        }
    }

//Various BrakeTypes that implement brakebehavior in their own way.
//DiskBrake Algorithm example 1
class DiskBrake : IBrakeBehavior
    {
        private static readonly int BrakeEfficiency = 2;

        public bool Brake(int speed, Condition condition, int distance)
        {
            switch (condition)
            {
                case Condition.dry:
                    return (speed * BrakeEfficiency) * 1 > distance ? false : true;
                case Condition.ice:
                    return (speed * BrakeEfficiency) * 1.7 > distance ? false : true;
                case Condition.snow:
                    return (speed * BrakeEfficiency) * 1.5 > distance ? false : true;
                case Condition.wet:
                    return (speed * BrakeEfficiency) * 1.2 > distance ? false : true;
                default:
                    return false;
            }
        }
    }

//DrumBrake Algorithm example 2
class DrumBrake : IBrakeBehavior
    {
        private static readonly int BrakeEfficiency = 3;

        public bool Brake(int speed, Condition condition, int distance)
        {
            switch (condition)
            {
                case Condition.dry:
                    return (speed * BrakeEfficiency) * 1 > distance ? false : true;
                case Condition.ice:
                    return (speed * BrakeEfficiency) * 1.7 > distance ? false : true;
                case Condition.snow:
                    return (speed * BrakeEfficiency) * 1.5 > distance ? false : true;
                case Condition.wet:
                    return (speed * BrakeEfficiency) * 1.2 > distance ? false : true;
                default:
                    return false;
            }
        }
    }

//ABSBrake Algorithm example 3
class ABSBrake : IBrakeBehavior
    {
        private static readonly int BrakeEfficiency = 1;

        public bool Brake(int speed, Condition condition, int distance)
        {
            switch (condition)
            {
                case Condition.dry:
                    return (speed * BrakeEfficiency) * 1 > distance ? false : true;
                case Condition.ice:
                    return (speed * BrakeEfficiency) * 1.7 > distance ? false : true;
                case Condition.snow:
                    return (speed * BrakeEfficiency) * 1.5 > distance ? false : true;
                case Condition.wet:
                    return (speed * BrakeEfficiency) * 1.2 > distance ? false : true;
                default:
                    return false;
            }
        }
    }

//Type of car using a certain braking algorithm
  public class ClassicCar : Car
    {
        public ClassicCar(IBrakeBehavior brakeBehave)
            : base(brakeBehave)
        { }
    }

//Another
 public class SportsCar : Car
    {
        public SportsCar(IBrakeBehavior brakeBehave)
            : base(brakeBehave)
        { }
    }

//Another
public class SUV : Car
    {
        public SUV(IBrakeBehavior brakeType)
            : base(brakeType)
        { }
    }