What is the difference between Facade and Template Method Pattern in C#? - c#

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.

Related

c# decorator pattern multiple properties wrapping multiple times [duplicate]

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 );

Why should I want to create an object with base class reference?

public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("I am Base Class");
}
public void BaseClassMethod()
{
Console.WriteLine("I am Base Class Method");
}
}
public class DerivedClass : BaseClass
{
public override void Display()
{
Console.WriteLine("I am Derived Class");
}
public void DerivedClassMethod()
{
Console.WriteLine("I am Derived Class Method");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
bc.Display();
bc.BaseClassMethod();
Console.WriteLine("--------------");
DerivedClass dc = new DerivedClass();
dc.Display();
dc.BaseClassMethod();
dc.DerivedClassMethod();
Console.WriteLine("--------------");
BaseClass bc2 = new DerivedClass();
bc2.Display();
bc2.BaseClassMethod();
//bc2.DerivedClass(); --> I can't reach b2.DerivedClass() method
Console.ReadLine();
}
}
Hi everyone. I am trying to clear my mind about Why and where would I want to create and use derived class object from base class reference. I know how virtual works. I know derived class is a base class and I can override virtual methods. I can reach non virtual methods in base class. But I want to know where could and why would I want to use this style of object creation. Like in my last part of the example code;
BaseClass bc2 = new DerivedClass();
I can't reach derived class methods so I cant use derived class methods. But it is still derived class because of the new DerivedClass. If I use normal DerivedClass d = new DerivedClass(); style, I can use both class methods. I just cant find any reason and situation I would want to use this style. I would be glad if anyone show me in which situation I have to use derived class object from base class reference so I can understand this style is exist in language. I want to know WHY, I am not asking why this isn't working or something like that. Just want to know situations. Thank you.
There are two main usages:
1) Collections of multiple types
Lets change your example a little bit
public class Shape
{
public virtual void Display()
{
Console.WriteLine("I am a Shape");
}
public void BaseClassMethod()
{
Console.WriteLine("I am Base Class Method");
}
}
public class Square : Shape
{
public override void Display()
{
Console.WriteLine("I am Square");
}
public void DerivedClassMethod()
{
Console.WriteLine("I am Derived Class Method");
}
}
public class Circle : Shape
{
public override void Display()
{
Console.WriteLine("I am Circle");
}
}
class Program
{
static void Main(string[] args)
{
List<Shape> shapes = new List<Shape();
shapes.Add(new Square());
shapes.Add(new Circle());
I have a list that can hold Circles, Squares, and generic Shapes all in a single collection.
2) Polymorphism
Continuing on from the previous code
foreach(Shape shape in shapes)
{
shape.Display();
}
we don't know what kind of Shape the variable shape is, however we do know that whatever kind it is it will have a Display() method we can call and it will show the correct information.
Polymorphism is useful when you need to call a function on something but you don't know the specific type that something will be because you are pulling a collection of base types like above, or you want to write a function that can take in any kind of Shape because the function does not need to know the specific kind to do it's work.
public static void LogDisplay(Shape shape)
{
Console.WriteLine("I am about to call shape.Display()");
shape.Display();
Console.WriteLine("I am just called shape.Display()");
}
My favorite example, because people can understand the use, is logging. Imagine I create a website. When I'm developing the site, I want to log to my file system, because it's easy to access. When I deploy the website, I want to log to the event log, because maybe I don't have direct access to the file system on that machine.
However, I only want to change where things are logged, I want the base class to structure how the actual text looks. So I have my base class that formats text:
public abstract class BaseLogger
{
public abstract void LogException(Exception ex);
public abstract void LogUserMessage(string userMessage);
protected string GetStringFromException(Exception ex)
{
//....
}
protected string GetStringFromUserMessage(string userMessage)
{
//....
}
}
Now I can have a class that logs to the File System:
public class FileLogger : BaseLogger
{
public FileLogger(string filename)
{
//initialize the file, etc
}
public override void LogException(Exception ex)
{
var string = GetStringFromException(ex);
File.WriteAllLines(...);
}
public override void LogException(Exception ex)
{
var string = GetStringFromUserMessage(ex);
File.WriteAllLines(...);
}
}
and my class that logs to the Event Log:
public class EventLogger : BaseLogger
{
public EventLogger()
{
//initialize the eventlog, etc
}
public override void LogException(Exception ex)
{
var string = GetStringFromException(ex);
EventLog.WriteEntry(...);
}
public override void LogException(Exception ex)
{
var string = GetStringFromUserMessage(ex);
EventLog.WriteEntry(...);
}
}
Now in my program, I only care that I have a BaseLogger when I inject one into my classes. The implementation details are irrelevant, I just know that I can LogException and LogUserMessage no matter what I'm using.
When I'm using the logger I benefit from not caring which derived class I use. That's the benefit of treating each derived class like a base class. I can swap them out without my program caring.
There are many reasons to do this, mostly to do with code re-usability and extensiblity, which in other words, to make a small change or enhancement easily without needing to rewrite a whole lot.
A real world example (which happens frequently) is the case where you have different customers using your software which may require you to support different databases (or even different table structures). So in order to do that, you can derive implementations from a common base class, and vary in the implementation details without affecting the rest of the program.
This also follows the design principle "Program
to an 'interface', not an 'implementation'" which is explained in the GoF design pattern book
public abstract class ProviderBase
{
public abstract Employee[] GetAllEmployees();
}
public class MySqlProvider:ProviderBase
{
public override Employee[] GetAllEmployees()
{
string select = "select * from employees";
//query from mysql ...
}
}
public class MsSqlProvider : ProviderBase
{
public override Employee[] GetAllEmployees()
{
string select = "select * from user u left join employee_record e on u.id=e.id";
//query from mysql ...
}
}
Then in the main program you may be able to change the type of database implementation by configuration or Dependency Injection
ProviderBase provider = null;
if(databaseType == "MySql")
{
provider = new MySqlProvider();
}
else if (databaseType == "MsSql")
{
provider = new MsSqlProvider();
}
var employees = provider.GetAllEmployees();
//do something
I believe a lot of the reasoning behind the availability of using derived classes has to do with minimizing repeated code.
To reference a real life example...
If I was to ask you to describe the attributes and abilities of a car, and then was to ask you to do the same for an electric car, you would find that much of the attributes and abilities are shared by both. So instead of having it be two completely separate classes, it would be more efficient to create the base class Car, and derive electricCar from that. Then you will only need to account for the specific differences of the electric car within the derived class, and all the shared attributes and abilities will carry over.
Hope this helps you understand the usefulness of base classes and derived classes. Very oversimplified but I feel it may help you grasp the concept!
The main reason to use a base class is reusability and polymorphism
So you could create the class depending on a condition:
BaseClass bc
if(case1)
bc = new DerivedClass1();
else
bc = new DerivedClass2();
In the following application you can use bc even if you don't know what kind of derived class it is at compile time. You can pass it e.g. to other functions and call the overridden methode:
bc.Display();
Derived class methods can only be used when you know what kind of derived class you actual have. Then you can do a conversion.
DerivedClass1 dc = bc as DerivedClass1;
dc.DerivedClassMethod()

Factory Pattern, Another Pattern or no pattern at all?

I have 2 cases wheter a method can be considered a Factory Design Pattern, this example is in C#, altought, can apply to other programming languages:
enum NinjaTypes {
Generic,
Katanna,
StarThrower,
Invisible,
Flyer
}
public class Ninja {
public string Name { get; set; }
public void jump() { ... }
public void kickAss() { ... }
}
public class KatannaNinja: Ninja {
public void useKatanna() { ... }
}
public class StarNinja: Ninja {
public void throwStar() { ... }
}
public class InvisibleNinja: Ninja {
public void becomeInvisible() {...}
public void becomeVisible() {...}
}
public class FlyNinja: Ninja {
public void fly() {...}
public void land() {...}
}
public class NinjaSchool {
// always return generic type
public Ninja StandardStudent() {...}
// may return other types
public Ninja SpecialityStudent(NinjaTypes WhichType) {...}
}
The method StandardStudent() always return a new object of the same type, the SpecialityStudent(...), may return new objects from different classes that share the same superclass / base type. Both methods are intentionally not virtual.
The question is, are both methods "Factory Design Pattern" ?
My guess is that SpecialityStudent(...) is, but StandardStudent() is not. If the second is not, can be considered another design pattern ?
I don't think that nor a FactoryMethod`nor AbstractFactory patterns forbid the user to use a parameter to specify a type to the creator method. Anyway you should consider at least 2 things in your design:
Factory methods are useful to keep the client unaware of the concrete type of the created object. From my point of view isn't wrong to specify explicitly the type of object to be created, but pay attention to not put too much knowledge on the client classes to be able to construct objects through the factory.
Both your factory methods return a Ninja object, but some of your ninjas extended class declare additional methods, which client is unaware of. If your client need to use those methods explicitly then maybe you have to make some consideration on your design.
I think this actually looks like an Anti-Pattern. There's really nothing to stop a consumer of this code to just instantiate the specialty ninjas directly. What benefit is there to using the Ninja School? I think the whole point of the Factory pattern is to encapsulate the process of instantiating an object so that you can hide the details from the consumer. Any time you make a change to the "creation" logic, it doesn't break anyone's code.
And it just looks like a bad idea to have all the types in an enum. I don't have a concrete reason to back up this claim other than, "it feels wrong".
After reviewing the Abstract Factory pattern, I can see how you could go about turning this into an Abstract Factory, but I don't see the benefit given the semantics of your objects. I think that if you want to have a Ninja factory, you'd have to make the individual constructors protected or internal, so they can't be called directly by consumer code
Both your methods can be seen as factories. But the second one is a little awkward to use:
var school = new NinjaSchool();
var ninja = school.SpecialtyStudent(NinjaTypes.Flyer);
// to fly you must cast
((FlyingNinja)ninja).Fly();
You've already asked for a flyer, so you shouldn't need to cast. A better option might be to eliminate the enum and ask for the exact ninja that you want:
var flyingNinja = school.FlyingStudent(); // you get a FlyingNinja
flyingNinja.Fly();
Another thing to consider in your design is this: what if you want an invisible ninja that can fly? Or a katana ninja that also throws stars? That will shake up your hierarchy and challenge your belief in inheritance.
It's almost a factory method. I would do something like:
enum NinjaTypes {
Generic, Katanna, StarThrower, Invisible, Flyer
}
class Ninja {
String Name;
void jump() {
}
void kickAss() {
}
void useKatanna() {
System.out.println("nothing happens");
}
void throwStar() {
System.out.println("nothing happens");
}
void becomeInvisible() {
System.out.println("nothing happens");
}
void becomeVisible() {
System.out.println("nothing happens");
}
void fly() {
System.out.println("nothing happens");
}
void land() {
System.out.println("nothing happens");
}
}
class StarThrowerNinja extends Ninja {
void throwStar() {
System.out.println("throwing star");
}
}
class NinjaSchool {
static Ninja create(NinjaTypes WhichType) {
switch (WhichType) {
case Generic:
return new Ninja();
case StarThrower:
return new StarThrowerNinja();
default:
return null;
}
}
}
public class Main {
public static void main(String[] args) {
Ninja generic=NinjaSchool.create(NinjaTypes.Generic);
generic.throwStar();
Ninja starThrower=NinjaSchool.create(NinjaTypes.StarThrower);
starThrower.throwStar();
}
}

Virtual Extension Methods?

I have a class that gets used in a client application and in a server application.
In the server application, I add some functionality to the class trough extension methods. Works great. Now I want a bit more:
My class (B) inherits from another class (A).
I'd like to attach a virtual function to A (let's say Execute() ), and then implement that function in B. But only in the server. The Execute() method would need to do stuff that is only possible to do on the server, using types that only the server knows about.
There are many types that inherit from A just like B does, and I'd like to implement Execute() for each of them.
I was hoping I could add a virtual extension method to A, but that idea doesn't seem to fly. I'm looking for the most elegant way to solve this problem, with or without extension methods.
No, there aren't such things as virtual extension methods. You could use overloading, but that doesn't support polymorphism. It sounds like you might want to look at something like dependency injection (etc) to have different code (dependencies) added in different environments - and use it in regular virtual methods:
class B {
public B(ISomeUtility util) {
// store util
}
public override void Execute() {
if(util != null) util.Foo();
}
}
Then use a DI framework to provide a server-specific ISomeUtility implementation to B at runtime. You can do the same thing with a central static registry (IOC, but no DI):
override void Execute() {
ISomeUtility util = Registry.Get<ISomeUtility>();
if(util != null) util.Foo();
}
(where you'd need to write Registry etc; plus on the server, register the ISomeUtility implementation)
You can use the new dynamic type functionality to avoid having to build a registry of types to methods:
using System;
using System.Collections.Generic;
using System.Linq;
using visitor.Extension;
namespace visitor
{
namespace Extension
{
static class Extension
{
public static void RunVisitor(this IThing thing, IThingOperation thingOperation)
{
thingOperation.Visit((dynamic)thing);
}
public static ITransformedThing GetTransformedThing(this IThing thing, int arg)
{
var x = new GetTransformedThing {Arg = arg};
thing.RunVisitor(x);
return x.Result;
}
}
}
interface IThingOperation
{
void Visit(IThing iThing);
void Visit(AThing aThing);
void Visit(BThing bThing);
void Visit(CThing cThing);
void Visit(DThing dThing);
}
interface ITransformedThing { }
class ATransformedThing : ITransformedThing { public ATransformedThing(AThing aThing, int arg) { } }
class BTransformedThing : ITransformedThing { public BTransformedThing(BThing bThing, int arg) { } }
class CTransformedThing : ITransformedThing { public CTransformedThing(CThing cThing, int arg) { } }
class DTransformedThing : ITransformedThing { public DTransformedThing(DThing dThing, int arg) { } }
class GetTransformedThing : IThingOperation
{
public int Arg { get; set; }
public ITransformedThing Result { get; private set; }
public void Visit(IThing iThing) { Result = null; }
public void Visit(AThing aThing) { Result = new ATransformedThing(aThing, Arg); }
public void Visit(BThing bThing) { Result = new BTransformedThing(bThing, Arg); }
public void Visit(CThing cThing) { Result = new CTransformedThing(cThing, Arg); }
public void Visit(DThing dThing) { Result = new DTransformedThing(dThing, Arg); }
}
interface IThing {}
class Thing : IThing {}
class AThing : Thing {}
class BThing : Thing {}
class CThing : Thing {}
class DThing : Thing {}
class EThing : Thing { }
class Program
{
static void Main(string[] args)
{
var things = new List<IThing> { new AThing(), new BThing(), new CThing(), new DThing(), new EThing() };
var transformedThings = things.Select(thing => thing.GetTransformedThing(4)).Where(transformedThing => transformedThing != null).ToList();
foreach (var transformedThing in transformedThings)
{
Console.WriteLine(transformedThing.GetType().ToString());
}
}
}
}
I would suggest something like the following. This code could be improved by adding support for detecting intermediate class hierarchy types that don't have a dispatch mapping and calling the nearest dispatch method based on the runtime hierarchy. It could also be improved by using reflection to detect overload of ExecuteInteral() and adding them automatically to the dispatch map.
using System;
using System.Collections.Generic;
namespace LanguageTests2
{
public class A { }
public class B : A {}
public class C : B {}
public static class VirtualExtensionMethods
{
private static readonly IDictionary<Type,Action<A>> _dispatchMap
= new Dictionary<Type, Action<A>>();
static VirtualExtensionMethods()
{
_dispatchMap[typeof(A)] = x => ExecuteInternal( (A)x );
_dispatchMap[typeof(B)] = x => ExecuteInternal( (B)x );
_dispatchMap[typeof(C)] = x => ExecuteInternal( (C)x );
}
public static void Execute( this A instance )
{
_dispatchMap[instance.GetType()]( instance );
}
private static void ExecuteInternal( A instance )
{
Console.WriteLine("\nCalled ToString() on: " + instance);
}
private static void ExecuteInternal(B instance)
{
Console.WriteLine( "\nCalled ToString() on: " + instance );
}
private static void ExecuteInternal(C instance)
{
Console.WriteLine("\nCalled ToString() on: " + instance);
}
}
public class VirtualExtensionsTest
{
public static void Main()
{
var instanceA = new A();
var instanceB = new B();
var instanceC = new C();
instanceA.Execute();
instanceB.Execute();
instanceC.Execute();
}
}
}
Virtual implies inheritance in a OOP way and extension methods are "just" static methods that through a bit a syntactic sugar the compiler allows you to pretend to call on an instance of the type of its first parameter. So no, virtual extension methods are out of the question.
Check out the answer by Marc Gravell for a possible solution to your problem.
You can implement a service register. Example (server side):
static IDictionary<Type, IService> serviceRegister;
public void ServerMethod(IBusinessType object)
{
serviceRegister[obect.GetType()].Execute(object);
}
What you need are rather services in your server, which implement server side functionality, instead of extension methods. I wouldn't put to much logic into extension methods.
Let me check: you have a class hierarchy inheriting from A, presumably structured according to your business domain. Then you want to add behaviours depending on where the classes execute. So far you've used extension methods, but now you find you cannot get them to vary with your class hierarchy. What kinds of behaviours are you attaching at the server?
If it's stuff like transaction management and security, policies implemented through dependency injection à la Marc's suggestion should work well. You could also consider implementing the Strategy pattern through delegates and lambdas, for a more limited version of DI. However, what's not clear is how client code currently uses your classes and their extension methods on the server. How dependent are other classes on how you add the server-side functionality? Are they server-side only classes that currently expect to find the extension methods?
In any case, it sounds like you're going to need a careful testability design and testing strategy since you are introducing variation along two simultaneous dimensions (inheritance hierarchy, execution environment). You are using unit testing, I trust? Check that whatever solution you choose (e.g. DI through configuration) interacts well with testing and mocking.

C# - using polymorphism in classes I didn't write

What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.

Categories

Resources