Introduce "Mandatory" Methods to Implementors of an Interface - c#

The current implementation is pretty much aligns with a simple Strategy Design Pattern. There are multiple steps to be executed and these will be invoked provided by the following interface:
public interface ICommandStep
{
void Execute(CommandParameters cParams);
string StepName { get; }
}
Example implementor:
public class Step1 : ICommandStep {
public string StepName => "Initial Step";
public void Execute(CommandParameters cParams) {
// instructions
}
}
By now there many different classes implementing this interface, and I want to ensure all of them will have a pre and post step to execution. For example log state, params, StepName start and end.
How could I introduce a way to have protected virtual void PreExecute and protected virtual void PostExecute methods with common (overridable) logic and to make sure the method will always be invoked in this order:
1. PreExecute
2. Execute
3. PostExecute
Preferably without changing the Execute method in the implementor classes.
Introducing abstract class is possible.

You can declare base class and define overridable methods in needed order:
public interface ICommandStep
{
void Execute(CommandParameters cParams);
string StepName { get; }
}
public abstract class CommandBase : ICommandStep
{
public void Execute(CommandParameters cParams)
{
PreExecute();
ExecuteInternal(cParams);
PostExecute();
}
protected virtual void PostExecute()
{
}
protected virtual void ExecuteInternal(CommandParameters cParams)
{
}
protected virtual void PreExecute()
{
}
public abstract string StepName { get; }
}
public class Step1 : CommandBase
{
public override string StepName => "Initial Step";
protected override void ExecuteInternal(object cParams)
{
// instructions
}
}

Adding new methods to the interface will necessarily mean breaking the existing implementations. If implementation is optional then you should use an abstract class instead of an interface.
An alternative exists by adding a new interface and adding a runtime type-check in an extension method, like so:
public interface ICommandStep
{
void Execute(CommandParameters cParams);
string StepName { get; }
}
public interface ICommandStep2 : ICommandStep
{
void PreExecute()
void PostExecute()
}
public static class Extensions
{
public static void Execute2(this ICommandStep step, CommandParameters cParams)
{
if( step is ICommandStep2 step2 )
{
step2.PreExecute();
step2.Execute( cParams );
step2.PostExecute();
}
else
{
step2.Execute( cParams );
}
}
}
Usage:
ICommandStep[] steps = ...
foreach( ICommandStep step in steps )
{
step.Execute2( cmdParams );
}

I can think of 2 solutions:
Template Method pattern as proposed by Backs.
Decorator Pattern together with factory. Decorator pattern is great when you want to execute some code before/after call to other object. Factory is to ensure that each created object will be decorated.
Example implementation of 2.:
using System;
namespace ConsoleApplication6
{
/// <summary>
/// This is the component in Decorator Pattern
/// </summary>
public interface ICommandStep
{
void Execute(String cParams);
string StepName { get; }
}
/// <summary>
/// This is the concrete component in Decorator Pattern
/// </summary>
public class ConcreteStep1 : ICommandStep
{
public string StepName
{
get
{
return "1";
}
}
public void Execute(string cParams)
{
Console.WriteLine($"STEP {StepName}: EXECUTE");
}
}
/// <summary>
/// This is the decorator in Decorator Pattern
/// </summary>
public abstract class StepDecorator : ICommandStep
{
protected ICommandStep _commandStep;
public abstract string StepName
{
get;
}
public StepDecorator(ICommandStep commandStep)
{
this._commandStep = commandStep;
}
public abstract void Execute(string cParams);
}
/// <summary>
/// This is the concrete decorator in Decorator Pattern
/// </summary>
public class ConcreteStepDecorator : StepDecorator
{
public ConcreteStepDecorator(ICommandStep commandStep) : base(commandStep) { }
public override string StepName
{
get
{
return _commandStep.StepName;
}
}
public override void Execute(string cParams)
{
// You can do whatever you want before / after execution of command
Console.WriteLine($"STEP {_commandStep.StepName}: PRE EXECUTE");
_commandStep.Execute(cParams);
Console.WriteLine($"STEP {_commandStep.StepName}: POST EXECUTE");
}
}
/// <summary>
/// This is a Simple Factory. You encapsulate here creation of ICommandStep, so that it will always be decorated
/// </summary>
public class SimpleStepFactory
{
public ICommandStep createStep()
{
return new ConcreteStepDecorator(new ConcreteStep1());
}
}
class Program
{
static void Main(string[] args)
{
var step = new SimpleStepFactory().createStep();
step.Execute("params");
Console.ReadLine();
}
}
}
This solution has couple of advantages:
You can wrap your steps with many decorators, i.e. you can wrap step in decorator that shows it's name and wrap these two in another decorator that shows the parameters
You don't have to modify your steps, because all the extra work is handled by decorators

Related

How to implement a factory pattern based on argument types?

I have PhotoBase class
public abstract class PhotoBase
{
public string Path { get; set; }
}
And I have multiple derived classes, for example the path may indicate a location in the file system or an external url.
public class FilePhoto : PhotoBase {}
public class ExternalPhoto : PhotoBase {}
I want to load these photos, I have a PhotoLoader class like below:
public class PhotoLoader
{
public void Load(FilePhoto Photo)
{
// get the photo from file system
}
public void Load(ExternalPhoto Photo)
{
// download the photo from path
}
}
Now I want to load these photos, so I have to do:
public class PhotoImporter
{
private PhotoLoader _photoLoader;
public PhotoImporter(PhotoLoader photoLoader)
{
_photoLoader = photoLoader;
}
public void ImportPhoto(PhotoBase photo)
{
if (photo is FilePhoto)
{
_photoLoader.Load(photo as FilePhoto);
}
if (photo is ExternalPhoto)
{
_photoLoader.Load(photo as ExternalPhoto);
}
}
}
I have several derived classes and I may add more photo types in the future. Is there a more elegant way that I could get rid of if conditions? Using factory pattern?
Another approach would be to have an abstract method Load on PhotoBase, that's then implemented by each subclass:
public abstract class PhotoBase
{
public string Path { get; set; }
public abstract void Load();
}
public class FilePhoto : PhotoBase
{
public override void Load()
{
// load from file system
}
}
public class ExternalPhoto : PhotoBase
{
public override void Load()
{
// load from path
}
}
That way, you can simply call the Load method on a PhotoBase:
public class PhotoImporter
{
public void ImportPhoto(PhotoBase photo)
{
photo.Load();
}
}
The main advantage is that each subclass implements the Load method, and therefore you can add as many subclasses as you want, without worrying about forgetting to implement it.
The main drawback to this implementation is that the Load methods can't depend on other dependencies. So for example, if one day you need to load a photo from a database, you can't pass the DBContext.
Proper to way to implement it which will make code easy to maintain is as follows:
public abstract class PhotoBase
{
public string Path { get; set; }
public abstract void Load(); // Have a abtract method
}
public class FilePhoto : PhotoBase {
public override void Load() { // Implement the abtract method
Console.WriteLine("FilePhoto");
}
}
public class ExternalPhoto : PhotoBase {
public override void Load() { // // Implement the abtract method
Console.WriteLine("ExternalPhoto");
}
}
public class PhotoLoader
{
private PhotoBase _PhotoBase;
public PhotoLoader(PhotoBase photoBase) { // Resolved by Dependency Injection
_PhotoBase = photoBase;
}
public void Load()
{
_PhotoBase.Load();
}
}
public class PhotoImporter
{
private PhotoLoader _photoLoader;
public PhotoImporter(PhotoLoader photoLoader) // Resolved by Dependency Injection
{
_photoLoader = photoLoader;
}
public void ImportPhoto()
{
_photoLoader.Load();
}
}
You need to have Dependency Injection define so that specified implementation will get resolved and appropriate 'Load' method will be invoked.
void Main()
{
// Following dependency should be resolved by Dependency Injection
PhotoBase filePhotoBase = new FilePhoto();
PhotoLoader filePhotoLoader = new PhotoLoader(filePhotoBase);
PhotoImporter filePhotoImporter = new PhotoImporter(filePhotoLoader);
PhotoBase externalPhotoBase = new ExternalPhoto();
PhotoLoader externalPhotoLoader = new PhotoLoader(externalPhotoBase);
PhotoImporter externalPhotoImporter = new PhotoImporter(externalPhotoLoader);
filePhotoImporter.ImportPhoto(); // Shows output 'FilePhoto'
externalPhotoImporter.ImportPhoto(); // Shows output 'ExternalPhoto'
}
You can have as much implementation as you want, but you need to have proper instance of PhotoImporter by Dependency Injection. Everything else will work smoothly.
This is how I could do this:
public class PhotoImporter
{
private PhotoLoader _photoLoader;
public PhotoImporter(PhotoLoader photoLoader)
{
_photoLoader = photoLoader;
}
public void ImportPhoto(PhotoBase photo)
{
var childType = photo.GetType();
dynamic childPhoto = Convert.ChangeType(photo, childType);
_photoLoader.Load(childPhoto);
}
}
You can simplify your ImportPhotoby using pattern matching:
public void ImportPhoto(photoBase photo)
{
switch(photo)
{
case FilePhoto filePhoto:
loader.Load(filePhoto);
break;
case ExternalPhoto externalPhoto:
loader.Load(externalPhoto);
break;
}
}
But this is only syntactic sugar and doesn't solve your real problem. What might help is a abstract Load method in your base class:
public abstract class PhotoBase
{
public string Path { get; set; }
public abstract void Load();
}
You have to implement this method in your child classes. If you call the method, the correct implementation will be chosen.
Online demo: https://dotnetfiddle.net/LfkxBQ

abstract class with multiple constructors in C#

I have a Command class that I want to parse to string / from string to send it as a UDP message. The base class look as simple as:
public abstract class Command
{
public Command() {}
public abstract override string ToString();
public abstract void FromString(string str);
}
From here I derive classes like
public class NetCommand : Command
{
public string details;
public NetCommand() {};
public override string ToString() {return details;}
public override void FromString(string str) {details = str; }
}
Or a bit more complex MovementCommand : Command that containes x,y,z doubles that get parsed and so on.
How can I add a constructor in the base class that takes string and uses the FromString method?
Is going to have the same exact code for all derived classes and it is going to look like:
public Command(string str)
{
this.FromString(str);
}
and each class will fill its own members from the string using its own FromString method.
But I'm lost with the syntax, any help?
this is exactly what you are asking for, including changes to abstract class:
public abstract class Command
{
public Command() { }
public Command(string str)
{
FromString(str);
}
public abstract override string ToString();
public abstract void FromString(string str);
}
public class NetCommand : Command
{
public string details;
public NetCommand() {}
public NetCommand(string str) : base(str) { }
public override string ToString() { return details; }
public override void FromString(string str) { details = str; }
}
The way I understand you is that you want to have a base class constructor that creates a sub class object. You can't do that.
What you can do is create a static factory method on the base class that creates the concrete objects based on the given string, e.g.
public abstract class Command
{
public Command() {}
public abstract override string ToString();
public abstract void FromString(string str);
public static Command FromString(string str){
Command command;
if(/*string indicates it is a NetCommand*/){
command = new NetCommand();
command.FromString(str);
}
}
}
Have a backing field that stores the value passed through the constructor and then two virtual methods that set and return that value. Note that in the below implementation the NetCommand can only be instantiated with non-parameterless constructor.
public abstract class Command
{
private string _details;
protected Command()
{
}
protected Command(string details)
{
_details = details;
}
public new virtual string ToString()
{
return _details;
}
public virtual void FromString(string details)
{
_details = details;
}
}
public class NetCommand : Command
{
public NetCommand(string str) : base(str)
{
}
}
I suggest this implementation (put as many code into base class as possible in order to ease further classes creation)
public abstract class Command {
protected Command(): this(null) {
}
protected Command(String details) {
Details = details;
}
// I'd rather convert it into property
public String Details {
get;
set; // may be "private set" will be better here
}
public override string ToString() {
return Details;
}
// TODO: think on delete or redesign this method:
// Redundant: Details provide all the functional required
// Bad name: "FromString" usually means create/return
// instance by given details
// public static Command FromString(string details)
public virtual void FromString(String details) {
Details = details;
}
}
...
public class NetCommand: Command {
public NetCommand(string details) : base(details) {
}
}
Expanding on Domysee's answer, using a generic factory method you could do the following:
public abstract class Command
{
protected Command() {}
public abstract override string ToString();
protected abstract void FromString(string str);
public static T FromString<T>(string str) where T: Command, new()
{
var command = new T();
command.FromString(str);
return command;
}
}
Now, as long as the derived Command has a default constructor, you can create instances of it using Command.FromString like this:
var command = Command.FromString<NetCommand>("command string");

Design pattern suggestion needed

I need a programming pattern but I couldn't figure out what it will be. I am not even sure if what I want is possible or not. Lets say I have a Class A and 10 class inherited from A. What I want is call the same method Method Print() implemented differently on each inherited class, but all of them need to repeat a same method of Class A.
Class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
}
Class A_1 : A
{
public override void Print()
{
StartingProcedure();
/// class specific print operation
EndingProcedure();
}
}
Class A_2 : A
{
public override void Print()
{
StartingProcedure();
/// class specific print operation
EndingProcedure();
}
}
As you see I dont want to keep writing StartingProcedure(); on each overridden Print method. I want to automate that procedure, when I inherit a new class from A I don't want to mind the Starting and Ending procedures, i want to just write the class specific print operation. Is there any pattern that will provide me this kind of a class behaviour?
BTW I work with C#
Class A
{
public void Print()
{
StartingProcedure();
SpecificPrint();
EndingProcedure();
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
protected virtual SpecificPrint() // could possibly be abstract
{
}
}
Class A_1 : A
{
public override void SpecificPrint()
{
/// class specific print operation
}
}
Class A_2 : A
{
public override void SpecificPrint()
{
/// class specific print operation
}
}
The pattern you are looking for in this case is the Template Pattern by Gang of Four (GoF).
Class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
Print();
}
protected void EndingProcedure()
{
/// something
}
}
usually you'll add another method called the Template Method:
/// Template Method
protected void Run()
{
StartingProcedure();
Print();
EndingProcedure();
}
class A_1 : A
{
public override void Print()
{
/// class specific print operation
}
public A_1()
{
base.Run();
}
}
As an alternative to Rik's answer, if you can change the class hierarchy, and you really don't want to call the base methods in the derived methods, you can use composition instead of inheritance to accomplish this. By using the decorator pattern, you can specify a print method that wraps the derived functions.
class PrintDecorator : A
{
private A wrappedA;
public PrintDecorator(A a)
{
wrappedA = a;
}
public virtual void Print()
{
//wrap the derived logic with the pre- and post- processing
StartingProcedure();
wrappedA.Print();
EndingProcedure();
}
}
class A
{
public virtual void Print()
{
}
protected void StartingProcedure()
{
/// something
}
protected void EndingProcedure()
{
/// something
}
}
class A_1 : A
{
public override void Print()
{
/// class specific print operation
}
}
class A_2 : A
{
public override void Print()
{
/// class specific print operation
}
}
Example usage:
A dec = new PrintDecorator(new A_1());
dec.Print();

"Base class params are not always used" code smell

Suppose you had such code:
public Base
{
abstract void Register();
}
public Registrator1: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
public Registrator2: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
But When you receive a new business rule asking you to write Registrator3 which actually registers based on some parameter and you change your code base to the next:
public Base
{
abstract void Register(externalParam);
}
public Registrator1: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate theUI
}
}
public Registrator2: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate the UI
}
}
public Registrator3: Base
{
override void Register(externalParam)
{
//uses a DDD - service passed in the params to populate the UI
}
}
But Registrator1 and Registrator2 do not need that param and the code becomes smelly. What are the ways to re-write this code?
You could use an object as a parameter here; which is commonly used in scenarios where the number of parameters can vary depending on the call being used.
struct RegistrationInfo
{
public static readonly RegistrationInfo Empty = new RegistrationInfo();
public string Username;
public string CustomerName;
public string Validity;
}
abstract class Base
{
public abstract void Register(RegistrationInfo info);
// If you want to retain the paramaterless call:
public void Register()
{
Register(RegistrationInfo.Empty);
}
}
class Registrar1 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.Username == null) throw new ArgumentNullException("info.Username");
}
}
class Registrar2 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.CustomerName == null) throw new ArgumentNullException("info.CustomerName");
}
}
This has the advantage that you don't need to change method parameters (which is breaking interface) each time a parameter is added. The usage also becomes somewhat self-documenting:
var r = new Registrar1();
r.Register(new RegistrationInfo(){ Username = "JimJoe" });
r.Register(RegistrationInfo.Empty);
It's like air freshener for this type of code smell, while it's still smelly; you can make it smell nicer.
Finally you can make the call-site cleaner by making it a params argument (this has a small amount of overhead); in all honesty though it is more smelly because it's a language hack. Finally you could improve it with generics:
class RegistrationInfo
{
}
class RegistrationInfo1 : RegistrationInfo
{
public string Arg;
}
class RegistrationInfo2 : RegistrationInfo
{
public int Arg;
}
interface IBase<in TRegistration>
where TRegistration : RegistrationInfo
{
void Register(TRegistration registration);
}
class Base : IBase<RegistrationInfo>
{
public void Register(RegistrationInfo registration)
{
}
}
class Registrar1 : IBase<RegistrationInfo1>
{
public void Register(RegistrationInfo1 arg)
{
}
}
class Registrar2 : IBase<RegistrationInfo2>
{
public void Register(RegistrationInfo2 arg)
{
}
}
Is it not possible to contain the logic for externalParam in Registrator3?
In other words, Registrator3 uses the param, then calls the unmodified parameterless base?
A lot really depends on where the logic belongs. If it is something intrinsic to the base, then put it in the base, and either overload the Register() function or supply a default value for the param so that sub classes don't need to provide it.
Assuming you want to reuse the registration logic from the base class, you could update the code as follows:
public class Base
{
public virtual void Register(object externalParam)
{
// base registration logic goes here
}
}
public class Registrator1: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator2: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator3: Base
{
public override void Register(object externalParam)
{
base.Register(externalParam);
// custom registration logic goes here
}
}
HTH,
Cosmin
EDIT: Updated code to compile.

Understanding Adapter Pattern

I am trying to understand Adapter pattern and its use in real world. After going through various articles on internet and www.dofactory.com, I created this sample code. I just want to know whether my understanding is correct. In the example below I have created MSDAO object in the Adaptor class. Later I changed it to OracleDAO.
class Client
{
static void Main(string[] args)
{
ITarget objAdapter = new Adapter();
object dummyObject = objAdapter.GetData();
}
}
Interface ITarget
{
public void GetData();
}
//Decision to use MSDAO
class Adapter : ITarget
{
public void GetData()
{
MSDAO objmsdao = new MSDAO();
objmsdao.GetData();
}
}
//After a month, the decision to use OracaleDAO was taken, so the code change
class Adapter : ITarget
{
public void GetData()
{
OracleDAO objoracledao = new OracleDAO();
objoracledao.GetData();
}
}
Generally the adapter pattern transforms one interface into another, but it can simply wrap the behavior to isolate your class from the underlying implementation. In your case, you are using an adapter, but you could just as easily have defined the DAO objects to simply implement the interface and programmed against the interface. The adapter pattern is usually used when you don't have control over the target class. My primary use of the adapter pattern would be to create wrappers for a framework class that doesn't implement an interface.
Say I want to mock out a framework class which doesn't implement an interface (and doesn't have virtual methods). With many mocking apis this is hard or impossible to do. What I will do, then, is define my own interface as a subset of the signature of the class I'm targeting. I implement a wrapper class that implements this interface and simply delegates the calls to the wrapped framework class. This wrapper class works as an adapter for the framework class. My classes use this adapter instead of the framework class, but get the framework class' behavior.
public interface IFoo
{
void Bar();
}
public class FooWrapper : IFoo
{
private FrameworkFoo Foo { get; set; }
public FooWrapper( FrameworkFoo foo )
{
this.Foo = foo;
}
public void Bar()
{
this.Foo.Bar();
}
}
Consider also the case where you have a couple of different classes that have basically the same functionality, but different signatures and you want to be able to use them interchangeably. If you can't transform these (or don't want to for other reasons), you may want to write an adapter class that defines a common interface and translates between that interface's methods and the methods available on the target classes.
Framework classes:
public class TargetA
{
public void Start() { ... }
public void End() { ... }
}
public class TargetB
{
public void Begin() { ... }
public void Terminate() { ... }
}
An adapter for them
public interface ITargetAdapter
{
void Open();
void Close();
}
public class AdapterA : ITargetAdapter
{
private TargetA A { get; set; }
public AdapterA( TargetA a )
{
this.A = a;
}
public void Open() { this.A.Start(); }
public void Close() { this.A.End(); }
}
public class AdapterB : ITargetAdapter
{
private TargetB B { get; set; }
public AdapterB( TargetB a )
{
this.B = a;
}
public void Open() { this.B.Begin(); }
public void Close() { this.B.Terminate(); }
}
Then used as:
ITargetAdapter adapter = new AdapterA( new TargetA() );
adapter.Open();
adapter.Close();
internal class Program
{
private static void Main(string[] args)
{
// When in foreign countries, and you want to say hello
// just say "hello" and then
// the appropriate non-English response comes out
// When in Japan:
var translator = new JapaneseTranslator(new JapaneseSpeaker());
EnglishMan freddie = new EnglishMan(translator);
// Freddie greets Tokyo, though he doesn't know a word of Japanese
Console.WriteLine(freddie.Greetings()); // "teo torriatte!"
// when in France:
ITarget translator2 = new FrenchTranslator(new FrenchSpeaker());
EnglishMan brian = new EnglishMan(translator2);
// Brian greets the crowd in Paris, though he doesn't know a word in French
Console.WriteLine(brian.Greetings());
// "So très charmant my dear! Bonjour"
// alternatively, the translators can also do the greeting:
Console.WriteLine(translator.Greetings()); // "Konichiwa, hisashiburi!"
Console.WriteLine(translator2.Greetings()); // "Bonjour!"
}
/// <summary>
/// This is the client.
/// </summary>
public class EnglishMan : ITarget
{
private ITarget target;
public EnglishMan(ITarget target)
{
this.target = target;
}
public string Greetings()
{
return target.Greetings();
}
}
/// <summary>
/// The target interface
/// </summary>
public interface ITarget
{
string Greetings();
}
/// <summary>
/// This is the adaptor
/// </summary>
public class JapaneseTranslator : ITarget
{
private JapaneseSpeaker japanese;
public JapaneseTranslator(JapaneseSpeaker japanese)
{
this.japanese = japanese;
}
public string Greetings()
{
return japanese.Konnichiwa();
}
}
/// <summary>
/// This is the adaptee
/// </summary>
public class JapaneseSpeaker
{
public JapaneseSpeaker()
{
}
public string Konnichiwa()
{
return "Konichiwa, hisashiburi!";
}
}
/// <summary>
/// This is the adaptor
/// </summary>
public class FrenchTranslator : ITarget
{
private FrenchSpeaker french;
public FrenchTranslator(FrenchSpeaker french)
{
this.french = french;
}
public string Greetings()
{
return french.Bonjour();
}
}
/// <summary>
/// This is the adaptee
/// </summary>
public class FrenchSpeaker
{
public string Bonjour()
{
return "Bonjour!!";
}
}
}
A canonical example inside the .NET framework exists in the System.Drawing.Bitmap class.
This Bitmap has a constructor that lets you load an image from a Stream:
public Bitmap(
Stream stream
)
what you don't know, is that internally the .NET Bitmap class is a wrapper around the GDI+ Bitmap class, and its constructor that takes an IStream:
Bitmap(
[in] IStream *stream,
[in] BOOL useIcm
);
So in the C# world, when i call:
new Bitmap(stream);
it has to turn around and call:
IStream stm;
IntPtr gpBitmap;
GdipCreateBitmapFromStream(stm, out gpBitmap);
The question is how to present a .NET Stream object to a method that expects a COM IStream interface.
Hence the internal GPStream class:
internal class GPStream : IStream
{
GPStream(Stream stream) { ... }
}
You need to present an IStream interface to your Stream object:
IStream Stream
======================================= =====================================
int Read(IntPtr buf, int len); --> int Read(byte[] buffer, int offset, int count)
int Write(IntPtr buf, int len); --> void Write(byte[] buffer, int offset, int count);
long Seek(long dlibMove, int dwOrigin); --> long Seek(long offset, SeekOrigin orgin)
... ...
So now you have an adapter:
And the code is something like:
IStream stm = new GPStream(stream); //adapter to convert Stream --> IStream
IntPtr gpBitmap;
GdipCreateBitmapFromStream(stm, out gpBitmap);
A very simple example...
interface ITarget
{
List<string> GetProducts();
}
public class VendorAdaptee
{
public List<string> GetListOfProducts()
{
List<string> products = new List<string>();
products.Add("Gaming Consoles");
products.Add("Television");
products.Add("Books");
products.Add("Musical Instruments");
return products;
}
}
class VendorAdapter:ITarget
{
public List<string> GetProducts()
{
VendorAdaptee adaptee = new VendorAdaptee();
return adaptee.GetListOfProducts();
}
}
class ShoppingPortalClient
{
static void Main(string[] args)
{
ITarget adapter = new VendorAdapter();
foreach (string product in adapter.GetProducts())
{
Console.WriteLine(product);
}
Console.ReadLine();
}
}
I’ll keep it very simple. What if one caller wants to call the GetData method of MSDAO and other caller wants OracleDAO.
Or in future other class can also be added.
In that case your solution will not work.
So I would suggest to declare the GetData method as virtual of the adaptee class.
Add a new adapter class, extend the adaptee class and implement your ITarget interface and implement the GetData (declare it override) method accordingly.
Repeat the above step if you will have new class in future.

Categories

Resources