I would like to create two algorithm with design pattern approach. Robot should clean and return to the initial position.
After clean the room, i need the cleaned path also.
I am planing to use the Command pattern.But one doubt, requirement says both clean and return algorithem should be interchangable and required two algorithem...so i havae a doubt Stratagy is better than Command pattern?
As per command pattern I can store all the executed commands in a List and find out the path. But still I have a doubt which pattern will be best(requirement says two ago required).
Please see the design , clean and return from different interface so i think it is difficult to use factory to make interchangable...
public interface ICleaningAlgorithm {
void Clean(IRobot robot);
}
public interface IReturnAlgorithm {
void Return(IRobot robot);
}
Example classes (without implementation):
public class CleaningAlgorithm : ICleaningAlgorithm {
public void Clean(IRobot robot) {
/* pseudocode from the post */
}
}
public class ReturnAlgorithm {
public void Return(IRobot robot) {
/* some shortest path algorithm */
}
}
Design UML image attached
If you need to have two algorithms that are interchangeable at runtime, then you should look into the Factory pattern, and the Command Pattern. As Oded said, design patterns are not mutually exclusive.
For example
public interface Command
{
// First, you define a common interface for all commands.
public void execute();
}
public class Command1 implements Command
{
// Implement the execute method.
public void execute()
{
// Run some code in here.
}
}
public class Command2 implements Command
{
// Implement the execute method for the second command.
public void execute()
{
// Run some more code in here.
}
}
So, now you've defined a common interface for your commands, which means they can be referenced like this:
Command com = new Command2();
// This is an important property!
Now you will implement your Factory class:
public class CommandFactory
{
public static int ALGO_1 = 1;
public static int ALGO_2 = 2;
public Command getInstance(int discriminator)
{
// Check the value, and if it matches a pre-defined value..
switch(discriminator)
{
case ALGO_1:
return new Command1();
break;
case ALGO_2:
return new Command2();
break;
}
}
}
This means you now have a more flexible way of generating these classes, and you can use this class as follows:
CommandFactory factory = new CommandFactory();
Command com = factory.getInstance(CommandFactory.ALGO_1);
// You've just generated algorithm 1.
com.execute();
// And you've just ran the code in algorithm 1.
Edit in response
My question is, why define different interfaces? Why not have it like:
public interface Algorithm {
void execute(IRobot robot);
}
public class CleaningAlgorithm : Algorithm {
public void execute(IRobot robot) {
/* pseudocode from the post */
}
}
public class ReturnAlgorithm : Algorithm {
public void execute(IRobot robot) {
/* some shortest path algorithm */
}
}
Related
I just started to learn Decorator Design Pattern, unfortunately i had to go through various refrences to understand the Decorator pattern in a better manner which led me in great confusion. so, as far as my understanding is concern, i believe this is a decorator pattern
interface IComponent
{
void Operation();
}
class Component : IComponent
{
public void Operation()
{
Console.WriteLine("I am walking ");
}
}
class DecoratorA : IComponent
{
IComponent component;
public DecoratorA(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("in the rain");
}
}
class DecoratorB : IComponent
{
IComponent component;
public DecoratorB(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("with an umbrella");
}
}
class Client
{
static void Main()
{
IComponent component = new Component();
component.Operation();
DecoratorA decoratorA = new DecoratorA(new Component());
component.Operation();
DecoratorB decoratorB = new DecoratorB(new Component());
component.Operation();
Console.Read();
}
}
But can the below code also be Decorator Pattern?
class Photo
{
public void Draw()
{
Console.WriteLine("draw a photo");
}
}
class BorderedPhoto : Photo
{
public void drawBorder()
{
Console.WriteLine("draw a border photo");
}
}
class FramePhoto : BorderedPhoto
{
public void frame()
{
Console.WriteLine("frame the photo");
}
}
class Client
{
static void Main()
{
Photo p = new Photo();
p.Draw();
BorderedPhoto b = new BorderedPhoto();
b.Draw();
b.drawBorder();
FramePhoto f = new FramePhoto();
f.Draw();
f.drawBorder();
f.frame();
}
}
My Understanding
From the second example given by me, we can call all the three methods, but from the first example i wont be able to get access to all the three methods by creating a single object.
It should be a comment, but I have too many words.
For example, you have an object and interface, like Repository : IRepository.
public interface IRepository
{
void SaveStuff();
}
public class Repository : IRepository
{
public void SaveStuff()
{
// save stuff
}
}
and client, which probably was written by someone else
class RepoClient
{
public void DoSomething(IRepository repo)
{
//...
repo.SaveStuff();
}
}
And once you decided, that ALL calls to repository should be logged. But you have a problem: the Repository class is from an external library and you don't want to change that code. So you need to extend the Repository's behavior that you use. You write RepositoryLogDecorator : IRepository, and inside on each method do the logging, like
public class RepositoryLogDecorator : IRepository
{
public IRepository _inner;
public RepositoryLogDecorator(IRepository inner)
{
_inner = inner;
}
public void SaveStuff()
{
// log enter to method
try
{
_inner.SaveStuff();
}
catch(Exception ex)
{
// log exception
}
// log exit to method
}
}
So, before you could use client as
var client = new RepoClient();
client.DoSomething(new Repository());
but now you can use
var client = new RepoClient();
client.DoSomething(new RepositoryLogDecorator(new Repository()));
Note, that this is a very simple example. In real projects, where object created primary with DI container, you will be able to use decorator by changing some config.
So, decorator is used to extend functionality of object without changing object or client.
Another benefit of decorator: your decorator does not depend on Repository implementation. Only depends from an interface IRepository. Why this is an advantage? If somehow you decide to write you own implementation of IRepository
public class MyAwesomeRepository : IRepository
{
public void SaveStuff()
{
// save stuff, but AWESOME!
}
}
you will be able to automatically decorate this with decorator, which already exist
var client = new RepoClient();
client.DoSomethig(new RepositoryLogDecorator(new MyAwesomeRepository()));
Want to see example from real software? (just as sample, code is ugly, I know) => go here
There is this PatternCraft series on Youtube that explains Design Patterns with Starcraft, you should check the video about Decorators here.
In the video above the author gives an example with a Marine and WeaponUpgrade.
In the game you will have a Marine and then you can upgrade its weapon:
marine = new WeaponUpgrade(marine);
Note that you still have a marine there, it is not a new unit, it is the same unit with things that modifies its attributes.
public class MarineWeaponUpgrade : IMarine
{
private IMarine marine;
public MarineWeaponUpgrade(IMarine marine)
{
this.marine = marine;
}
public int Damage
{
get { return this.marine.Damage + 1; } // here
set { this.marine.Damage = value; }
}
}
You do that by creating a class that implements the same interface as your unit and access your unit properties to modify values.
There is a Kata on CodeWars challenging you to complete the Weapon and Armor decorators for a marine.
Per GOF page Decorator desing pattern:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
In your second example you are using inheritance to extend behaviour of a class, I believe this is technically not a Decorator design pattern.
The decorator pattern allows you to add a specific behavior to an individual object of a given type without affecting other instances of that same type.
In your second example, which is normal inheritance, all instances of the class inherit the modified behavior.
The second example is not a decorate pattern, since an essential ingredient to decorator pattern is that the object accepts one of its kind and possibly enhance it.
An instances of this in the first example is
public DecoratorA(IComponent c)
{
component = c;
}
Also, the goal of the decorator pattern is to create "one" object, then decorate it by passing it through different filters or decorators.
Hence the line
DecoratorA decoratorA = new DecoratorA(new Component());
Should be
DecoratorA decoratorA = new DecoratorA(component );
What is the difference between a Facade and a Template method pattern? Both of them provide high level views of the subsystem and hide it from the user.
Facade Pattern
internal class SubsystemA
{
internal string A1()
{
return "Subsystem A, Method A1\n";
}
internal string A2()
{
return "Subsystem A, Method A2\n";
}
}
internal class SubsystemB
{
internal string B1()
{
return "Subsystem B, Method B1\n";
}
}
internal class SubsystemC
{
internal string C1()
{
return "Subsystem C, Method C1\n";
}
}
public static class Facade
{
static SubsystemA a = new SubsystemA();
static SubsystemB b = new SubsystemB();
static SubsystemC c = new SubsystemC();
public static void Operation1()
{
Console.WriteLine("Operation 1\n" +
a.A1() +
a.A2() +
b.B1());
}
public static void Operation2()
{
Console.WriteLine("Operation 2\n" +
b.B1() +
c.C1());
}
}
// ============= Different compilation
// Compile with csc /r:FacadeLib.dll Facade-Main.cs
class Client
{
static void Main()
{
Facade.Operation1();
Facade.Operation2();
}
}
Template pattern
interface IPrimitives
{
string Operation1();
string Operation2();
}
class Algorithm
{
public void TemplateMethod(IPrimitives a)
{
string s =
a.Operation1() +
a.Operation2();
Console.WriteLine(s);
}
}
class ClassA : IPrimitives
{
public string Operation1()
{
return "ClassA:Op1 ";
}
public string Operation2()
{
return "ClassA:Op2 ";
}
}
class ClassB : IPrimitives
{
public string Operation1()
{
return "ClassB:Op1 ";
}
public string Operation2()
{
return "ClassB.Op2 ";
}
}
class TemplateMethodPattern
{
static void Main()
{
Algorithm m = new Algorithm();
m.TemplateMethod(new ClassA());
m.TemplateMethod(new ClassB());
}
}
This example has been taken from O'Reilly Design Patterns
In the above provided example, both Facade and Template pattern Implement an interface and the uses an abstraction and defines on how the operation should be handled. I dont find any difference between the two patterns. Can anyone help me understand it.
Facade pattern will introduce new functionality by combining sub functionalities under wrapper method.
Facade class in this case have different structure then sub classes.
Template pattern provide skeleton of algorithm in the base class and gives possibility for derived classes to override/implement some units of this algorithm.
In this case classes derived from template have same structure as base class.
The main purpose of the template method pattern is to define some generic algorithm, where some implementation details might be specified by the derived classes.
Here is an example:
abstract class Car
{
public void Drive()
{
IgnitionOn();
EngineOn();
EngageTransmission();
}
protected abstract void IgnitionOn();
protected abstract void EngineOn();
protected abstract void EngageTransmission();
}
Here the Drive() method is a template method that defines the generic behavior (how to drive). But every derived class can (or, in this example, have to) provide implementation details.
Example:
class DieselCarWithManualGearbox : Car
{
protected override void IgnitionOn()
{
IgnitionControlModule.IgnitionState = IgnitionState.On;
}
protected override void EngineOn()
{
DieselEngine.StartFuelPump();
DieselEngine.Run();
}
protected override void EngageTransmission()
{
ManualGearbox.Gear = 1;
}
}
The DieselCarWithManualGearbox class provides some specific implementation, but the whole algorithm stays unchanged. Then you create some ElectroCarWithAutomaticGearbox that uses the same algorithm for driving, but needs its own ElectricEngine and AutomaticGearbox stuff to do it properly.
The facade pattern can be used to simplify the usage of some logic that is contained in multiple interfaces or modules. For example, the static class Console can be seen as a facade for console usage. It hides the implementation details and provides a couple of simple methods we can easily use. We cannot change the behavior of a facade though by providing some additional implementatons. That is the difference.
In simple words: The template method belongs to a base class and allows the subclasses to redefine some steps. You create an object of a class and invoke this template method to complete your job.
But facades often involve multiple objects from many different classes. This time you perform a series of steps to accomplish the task involving all these objects. You do not redefine the methods in these classes, instead, you manage to call them easily.
Now to aswer your question:
In your example, in the template pattern, see that you use only one object of the Algorithm. But it is not the case for a facade. Though you have used static objects, see how many different types of objects are involved there.
The following code is a valid C# construct that compile juste fine.
public class Weird : Weird.IWeird
{
private interface IWeird
{
}
}
What would be the possible uses of this?
Edit: This question is more specific that this one: "What is a private interface?". It shows that it's possible to implement a private interface from the parent type itself, which seems to be rather pointless. The only use I can think of would be a weird case of interface segregation where you would want to pass an instance of the parent class to a nested class instance as IWeird.
This is probably one of these situations in compiler development when prohibiting something has a higher cost than allowing it. Prohibiting this use would require writing and maintaining code to detect this situation, and report an error; if the feature works as-is, this is an additional work for the team, and it could be avoided. After all, perhaps someone with good imagination could figure out a way to use the feature.
As far as a useful example goes, one potential use is to make another implementation in the class, and use it as an alternative without exposing it to the users of the API:
public class Demo : Demo.Impl {
// Private interface
private interface Impl {
public bool IsValidState {get;}
void DoIt();
}
// Implementation for the error state
private class Error : Impl {
public bool IsValidState { get { return false; } }
public void DoIt() {
Console.WriteLine("Invalid state.");
}
}
private readonly string name;
// Implementation for the non-error state
public bool IsValidState { get { return true; } }
public void DoIt() {
Console.WriteLine("Hello, {0}", name);
}
// Constructor assigns impl depending on the parameter passed to it
private readonly Impl impl;
// Users are expected to use this method and property:
public bool IsValid {
get {
return impl.IsValidState;
}
}
public void SayHello() {
impl.DoIt();
}
// Constructor decides which impl to use
public Demo(string s) {
if (s == null) {
impl = new Error();
} else {
impl = this;
name = s;
}
}
}
As far as best practices go, this design is questionable at best. In particular, I would create a second nested class for the non-error implementation, rather than reusing the main class for that purpose. However, there is nothing terribly wrong with this design (apart from the fact that both IsValidState and DoIt are visible) so it was OK of the C# team to allow this use.
I've been having trouble even defining what I am looking for.
I am writing an app to determine winners in a tournament. I would like my base class to be able to change it's inheritance based on how many people are playing, given that multiple inheritance is not an option, and probably wouldn't be a very good one the more i think on it.
I see something along the lines of
class Base
{
//Constructor receiving the quantity of players
public Base (int quantityOfPlayers)
{
//Changes Base inheritance dynamically based on QuantityOfPlayers
switch (quantityOfPlayers)
{
case 4: (Base : FourPlayers);
case 5: (Base : FivePlayers);
}
}
}
But of course i can't seem to find a means (if there is one) of dynamically changing the inheritance like that. Otherwise I'm stuck using more complicated means though each of the getter and setter functions are going to be essentially the same.
Very good solutions. let me add that I'm using a GUI not the console.
I have to think on this, the factory class is good, but it has convinced me I'm over thinking my approach.
There is a software design pattern called strategy pattern for this kind of situation.
Define an interface for the game strategy
public interface IGameStrategy
{
// Things that depend on the number of players, go here...
}
The right strategy gets injected into the game through constructor injection
public class Game
{
private IGameStrategy _strategy;
// Constructor injection
public Game(IGameStrategy strategy)
{
_strategy = strategy;
}
// Things common to all types of games go here...
}
Define a factory method like this:
private IGameStrategy CreateGameStrategy(int numberOfPlayers)
switch (numberOfPlayers)
{
case 4:
return FourPlayersStrategy();
case 5:
return FivePlayersStrategy();
default:
throw new ArgumentException("Invalid number of players");
}
}
Then create a game like this:
var game = new Game(CreateGameStrategy(numberOfPlayers));
Of course the strategy classes implement the interface. They can do so directly or they can inherit a common abstract base class implementing the interface.
The game logic is split into things common to all types of games implemented in the Game class and things specific to the number of players implemented in the strategy classes.
You could create a factory class that generates the proper class based on the number of players:
public class PlayerQtyFactory
{
//You can add any other args you might need as well
public BaseClass CreatePlayerQty(int numPlayers)
{
switch (numPlayers)
{
Case 2:
return new TwoPlayers();
Case 3:
return new ThreePlayers();
{
}
}
Without knowing more about what you are trying to do, it is hard to say if this is the best approach, but it is certainly A aproach.
For this particular situation I would use a factoryesque (or just plan factory) solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tester
{
//declare common functionality
public interface ISharedFunctionality
{
//put all shared functionality here
void SomeMethod();
void SomeOtherMethod();
void DifferentMethod();
string Name {get;set;}
}
public interface ISinglePlayerFunctionality : ISharedFunctionality
{
//put single player functionality here
void SomeOtherMethod();
void SomeMethod();
}
public interface IMultiplePlayerFunctionality : ISharedFunctionality
{
//put multiplayer functionality here
void DifferentMethod();
void SomeMethod();
}
public class ImplementationBase : ISharedFunctionality
{
//shared implementation here
public void SomeMethod()
{
//do stuff
Console.WriteLine("In Base");
}
public void SomeOtherMethod()
{
//one you don't want to inherit in multiplayer
Console.WriteLine("In Base");
}
public void DifferentMethod()
{
Console.WriteLine("In Base");
}
public string Name
{
get;
set;
}
}
public class MultiPlayerImplementation : ImplementationBase, IMultiplePlayerFunctionality
{
//multiplay impl
// you inherit some method but don't want to inherit
//SomeOtherMethod when cast to ISharedFunctionality
void ISharedFunctionality.SomeMethod()
{
//when cast to ISharedFunctionality this method will execute not inherited
Console.WriteLine("In MutilPlayImplementation");
}
}
public class SinglePlayerImplementation : ImplementationBase , ISinglePlayerFunctionality
{
//singleplay impl
void ISharedFunctionality.SomeOtherMethod()
{
Console.WriteLine("In SinglePlayerImplementation" );
}
}
public class Factory
{
//logic to decide impl here
public ISharedFunctionality Create(int numberOfPlayer)
{
if (numberOfPlayer == 1)
{
return new SinglePlayerImplementation();
}
else if(numberOfPlayer > 1)
{
return new MultiPlayerImplementation();
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
var factory = new Factory();
var results = new[]{factory.Create(1) , factory.Create(2) };
int j=0;
foreach (var i in results)
{
///for single player will be base
///multiplaryer will be mutliplayer
i.SomeMethod();
//for single player will be single player
// for multiplayer will be base
i.SomeOtherMethod();
i.DifferentMethod();
i.Name = "Item-Number-" + j;
Console.WriteLine();
}
}
}
}
The benefit to this is two fold, you now no longer have ambiguity in terms of what method is being called, and you have a unified place to construct future implementations based off of similair contracts (i.e. three player behavior, different menu behavior, and it might be even less code if you want the exact same methods to just behave differently
I have a lot of different engines that implement different algorithms. All of them implement the same interface but have different Configuration methods. Most of them are configured without parameters, some of them with one integer and even less with two integers. There is a small probability that in the future we will have with three or even four integers.
I need to create a Engine controller that decides when it has to start or stop the engine as this is common for all of them. The options I thought are the following:
Create an unique interface with as much parameters as the biggest Configure method available and ignore the not needed ones at the engines. This way I'll have just only one EngineController.
Create an Interface for each of the different configure methods and create a EngineController for each one of the different interfaces (but this will make me create a lot of classes that only differ on the number of parameters and will require 2 new classes each time a new parameter is added to an engine.
...
I really don't feel comfortable with any of the two solutions as passing unneeded parameters looks 'ugly' and due to the high number of classes generated with the second option (that only have very minor differences).
Any design or pattern that avoids this problem?
EDIT (Thanks for the answers, this edit answers all of them and clarifies the question):
Just to give an example, these are the engines.
abstract class EngineBase
{
public void Start() {...}
public void Stop() {...}
}
class EngineOne : EngineBase
{
public void Configure(int parameter1) {...};
}
class EngineTwo : EngineBase
{
public void Configure(int parameter1, int parameter2) {...};
}
class EngineThree : EngineBase
{
public void Configure(int parameter1, int parameter2, int parameter3) {...};
}
As all the engines have the same logic to decide when to start or end I want to create a new class that handles them, called EngineController. The controller will call the Configure, the Start and the Stop when needed:
class EngineController
{
EngineBase _engine; ??? or what?
void SuperviseEngine() { ... _engine.Configure(x,x,...) ... _engine.Start() ...
}
The first idea I has is to add to the EngineBase class the next method:
abstract class EngineBase
{
public void Start() {...}
public void Stop() {...}
public void Configure(int parameter1, int parameter2, int parameter3) {...}
}
class EngineController
{
EngineBase _engine;
void SuperviseEngine() { ... _engine.Configure(x,y,z) ... _engine.Start() ...
}
and ignore the unneeded parameters but I don't like the idea. Then I thought on doing the following:
interface I1ParameterConfigurable
{
public void Configure(int parameter1) {...};
}
interface I2ParameterConfigurable
{
public void Configure(int parameter1, int parameter2) {...};
}
interface I3ParameterConfigurable
{
public void Configure(int parameter1, int parameter2, int parameter3) {...};
}
and then create 3 different controllers for each kind of engine:
class EngineController1Parameter
{
EngineBase _engine;
I1ParameterConfigurable _configurableEngine = _engine as I1ParameterConfigurable;
void SuperviseEngine() { ... _configurableEngine .Configure(x) ... _engine.Start()
}
class EngineController2Parameter
{
EngineBase _engine;
I2ParameterConfigurable _configurableEngine = _engine as I2ParameterConfigurable;
void SuperviseEngine() { ... _configurableEngine .Configure(x, y) ... _engine.Start()
}
You get the idea, but I feel that this will create a lot of interfaces / classes when maybe there is way to avoid this.
Thanks to your answers I have a third option that is similar to the 1st one but using an array (or IEnumerable or whatever) to pass a undefined number of parameters. The idea is not bad but then I'll lose the parameter names. But maybe it's the best option until now.
Will that help you.
interface IEngine
{
void startEngine(params int[] engineParam);
}
Maybe I don't fully understand but I think you want something like this:
public interface IEngineController //I dont see a need to expose the enigine here in this pseudo code
{
void Start();
IConfiguration Config { get; }
}
public interface IEngine
{
void Start();
}
public interface IConfiguration
{
bool IsOkToStart { get; }
}
public class Configuration : IConfiguration
{
public Configuration(List<IConfigurationParameter> configurationParameters)
{
ConfigurationParameters = configurationParameters;
}
public bool IsOkToStart
{
get { return ConfigurationParameters.All(cfg=>cfg.IsOkToStart); }
}
protected List<IConfigurationParameter> ConfigurationParameters { get; private set; }
}
public interface IConfigurationParameter
{
bool IsOkToStart { get; }
}
public interface IMaxTemp : IConfigurationParameter
{
double MaxTemp { get; }
}
public interface ISafetyParameter : IConfigurationParameter
{
ISafetyCondition SafetyCondition { get; }
}
This got a little long, I omitted Stop() for brevity. The idea is:
The controller has an IEngine (not exposed in the interface) and an IConfig
IEngine has the Start() method.
A Configuration is a list of IConfigparameters that has a bool is ok to start (if all parameters are ok).
Each parameter has an IsOkToStart that is calculated depending on some condition
Maybe this provides flexibility for you? Combine the parameters you need and possibly add ned parameters in the future. I believe it is a good thing that the interfaces are extremely small and cohesive. Maybe even split them into IStartParameter and IStopParameter and just combine to the desired config?
I would model it similar to this:
public interface IEngine1 {
}
public interface IEngine1Config {
int Param1 {get;}
}
public Engine1 : IEngine1 {
IEngine1Config _config;
public Engine1(IEngine1Config config) {
_config = config;
}
}
You could then optionally choose to have one class implementing the different engine configurations:
class AllEnginesConfig : IEngine1Config, IEngine2Config {
int Param1 {get;set;}
// ... etc
}
(of course, it may be better in your situation to implement the configs in separate classes also)
If you have a lot of engines, I would use an IoC container to register all the different types, and let it wire up all the dependencies.
container.Register<IEngine1, Engine1>();
var theOneAndOnlyConfig = new AllEnginesConfig() {}; // properly initialized, of course
container.RegisterInstance<IEngine1Config>(theOneAndOnlyConfig);
container.RegisterInstance<IEngine2Config>(theOneAndOnlyConfig);
// ...
Then, to instantiate an engine, you simply use the container:
container.Get<IEngine1>();
IOC containers to invoke a engine you require or bunch of engines you require and inject them at run time and you can use them in combination with optional parameters while invoking containers. I have seen usage of Optional parameters in many attributes of .NET FW. or use an list of object parameter to get all inputs and when called can parse the list and decide which engine it was intended to invoke. None of them will be hard to grasp and use