Is There a Name for this Pattern - c#

I've used this pattern many times in a variety of places, usually alongside a plugin pattern.
Some example ways I've used it are for messaging systems, such as creating subscribers to various types of unrelated messages. I've also used it for generic integration workflows that each need a differently shaped context object.
Basically the pattern consists of defining a blank marker interface for a message or context. Then defining a high level workflow interface that works with the message/context interface. You can then use a factory to get a concrete instance of the workflow, and if needed, the workflow can also be responsible for parsing its message / context from a common data format.
Next, you create an abstract generic base workflow whose responsibilty is just to map calls to the interface methods, which pass around the useless marker interface, into calls to abstract methods that take the concrete version of the message/context.
Hopefully that makes sense. I'll provide a code example below. I'd love to know if this pattern has a name because I've noticed that I've used it about 4-5 times now. Also, I'm just fleshing out how to explain the pattern, so if anything about my explanation doesn't make sense please let me know that as well.
The main point is that you can have multiple classes with different method signatures that can still be called via a common interface:
End Result
public class ConcreteA : Base<MessageA>
{
public void Process(MessageA message){...}
public MessageA Parse(IDictionary data){...}
}
public class ConcreteB : Base<MessageB>
{
public void Process(MessageB message){...}
public MessageB Parse(IDictionary data){...}
}
//And both can by called by...
public void Main(){
var data = GetDataFromIntegrationSource(someContext);
IWorkflow impl = Factory.GetConcrete(someContext);
//So in your classes you're able to work with strongly typed parameters,
//But in the consuming code you still can use a common interface
//Consuming code never even knows what the strong type is.
IMessage msg = impl.Parse(data);
impl.Process(msg);
}
FULL EXAMPLE
High Level Interfaces
public interface IGenericeMarkerInterface
{
}
public interface IGenericWorkflow
{
void Process(IGenericeMarkerInterface messageOrContext);
IGenericeMarkerInterface Parse(IDictionary<string, string> commonDataFormat);
}
Abstract Base for Mapping to Concrete Methods
public abstract class GenericWorkflowBase<T> : IGenericWorkflow where T : IGenericeMarkerInterface
{
public void Process(IGenericeMarkerInterface messageOrContext)
{
Process((T)messageOrContext);
}
public IGenericeMarkerInterface Parse(IDictionary<string, string> commonDataFormat)
{
return DoParse(commonDataFormat);
}
public abstract void Process(T messageOrContext);
public abstract T DoParse(IDictionary<string, string> commonDataFormat);
}
Mapping Attributes
public class MappingAttributeUsedByFactoryAttribute : Attribute
{
public WorkflowType SomePropertyForMapping { get; set; }
}
Concrete Implementations
public class SomeRandomlyShapedMessageOrContext : IGenericeMarkerInterface
{
public int ID { get; set; }
public string Data { get; set; }
}
[MappingAttributeUsedByFactory(WorkflowType.IntegrationPartnerB)]
public class ConcreteWorkflow : GenericWorkflowBase<SomeRandomlyShapedMessageOrContext>
{
public override void Process(SomeRandomlyShapedMessageOrContext messageOrContext)
{
//TODO: process the strongly typed message
}
public override SomeRandomlyShapedMessageOrContext DoParse(IDictionary<string, string> commonDataFormat)
{
//TODO: parse the common data into the strongly typed message
}
}
Factory
public static class WorkflowFactory
{
public static IGenericWorkflow Get(WorkflowType workflow)
{
//TODO: find the concrete workflow by inspecting attributes
}
}
Example Usage
public static class Program
{
public static void Main(string[] args)
{
//this could be driven by a UI or some contextual data
var someSortOfWorkflowIdentifier = (WorkflowType)args[0];
var data = GetSomeDictionaryOfData();
var workflow = WorkflowFactory.Get(someSortOfWorkflowIdentifier);
workflow.Process(workflow.Parse(data));
}
}

Yes, it's exactly same as you named it: Marker interface

Related

Parametrized Abstract Factory / Factory Method / other creation patterns

I want to have some factory (doesn't matter if Abstract Factory pattern or Factory Method - looks like the second is specific form of the first one. In my case only one object should be created). The thing is that although created products are similar, they depends on some arguments.
How to prepare this architecture in compliance with design patterns?
Current approach below
public abstract class Product {}
public class MyProduct : Product
{
public bool Abc { get; set; }
}
public class YourProduct : Product {}
public abstract class ProductFactory
{
//in some cases parameter not in use
public abstract Product Create(HelpData additionalData);
}
public class MyProductFactory : ProductFactory
{
public override Product Create(HelpData additionalData)
{
return new MyProduct {Abc = additionalData.SomethingImportantForMyProduct};
}
}
public class YourProductFactory : ProductFactory
{
//unused parameter
public override Product Create(HelpData additionalData)
{
return new YourProduct();
}
}
public class HelpData
{
public bool SomethingImportantForMyProduct { get; set; }
}
EDIT
I see it's not clear so will repeat.
Usually I'm not using patterns just because of using them. But this problem seems not to be border case. Looks rather quite frequent. Going further I believe there's design pattern suitable to this, but I'm not sure which one. For now looks like abstract factory is not right choice.
Don't use design-patterns because you're using design-patterns. Always have in mind when to use one and when not. In your circumstances at least the abstract factory-pattern is wrong, as it assumes all factories to work with the same parameters. So if you have different parameters you surely need different factories.
However there's no way for the abstract factory to guess how to get an instance of a HelpData in some case but not in the other, so either pass it to every abstract factory or completely omit this further abstraction and stay with two independent factories:
public abstract class Product {}
public class MyProduct : Product
{
public bool Abc { get; set; }
}
public class YourProduct : Product {}
public class MyProductFactory
{
public Product Create(HelpData additionalData)
{
return new MyProduct {Abc = additionalData.SomethingImportantForMyProduct};
}
}
public class YourProductFactory
{
//unused parameter
public Product Create()
{
return new YourProduct();
}
}
public class HelpData
{
public bool SomethingImportantForMyProduct { get; set; }
}
Exposing a parameter only used within one factory to all factories isn't a good idea.
Besides this just imagine you don't have factories but any other classes that have a Create-method, where one needs a parameter, but the other one does not. Why should those two classes derive from the same base-class (in your case the abstract factory), when the don't have any common members? There's apparently no reason for this, so don't overcomplicate things just for the sake of using a pattern which doesn't fit.
Depending on where and how you retrieve additional data you could inject that data to the factory which will use it to construct the object:
public abstract class ProductFactory
{
public abstract Product Create();
}
public class MyProductFactory : ProductFactory
{
private HelpData additionalData;
public MyProductFactory(HelpData additionalData)
{
this.additionalData = additionalData;
}
public override Product Create()
{
return new MyProduct {Abc = additionalData.SomethingImportantForMyProduct};
}
}
public class YourProductFactory : ProductFactory
{
public override Product Create()
{
return new YourProduct();
}
}
Instead of passing HelpData to constructor of a factory you could inject a service that knows how to retrieve HelpData specific to the object being created. You could pass some other parameter to Create method if it is used for both factories.
I have also googled a bit and found good answer that explains why not https://stackoverflow.com/a/6241219/2138959. Passing a dictionary or a type that has property of dictionary type is also and option but in such approaches client has too much knowledge of a type it want to be created to use abstract factory.

Implementing a Factory Pattern with CSLA.NET

I would like to implement Factory Pattern in CSLA. I can use an abstract base class or an interface for the abstraction. I have decided to use an abstract class, only because I have certain common functionality such as, saving to store, retrieving from store, and deletion of the record. Also, some properties that would apply to all implemented objects.
C# only allows for inheritance from one class, so I can either use BusinessBase or the abstract class. I would also like the concrete types to have their own set of business rules. How can this be done with CSLA?
If I do what I have listed below, will the rules in both the abstract class as well as the concrete class get fired?
Some code ...
Abstract class:
public class Form : BusinessBase<Form> {
private static PropertyInfo<string> FormNameProperty = RegisterProperty<string>(c => c.FormName);
public string FormName
{
get { return GetProperty(FormNameProperty); }
}
public abstract void LoadContent();
protected override void AddBusinessRules()
{
// business rules that are commmon for all implementations
}
}
Concrete implementation:
public class FormA : Form {
private static PropertyInfo<string> FirstNameProperty = RegisterProperty<string>(c => c.FirstName);
public string FirstName
{
get { return GetProperty(FirstNameProperty); }
}
public override void LoadContent(){
// some custom code
}
protected override void AddBusinessRules()
{
// business rules that only apply to this class
}
}
Factory:
public static class FormFactory{
public static Form GetForm(string formanmae) {
Type formType = GetFormType(formName);
if(formType == null)
return null;
var form = Activator.CreateInstance(formType) as ReferralForm;
return form;
}
}
Instead of using Activator.CreateInstance, you should use the Csla DataPortal.
var form = (Form)Csla.DataPortal.Create(formType, new Csla.Server.EmptyCriteria);
This way you are creating your business object using the Csla way, so any rules that should be run will be.

How to not violating the OCP when you want to choose between different classes which are inherited from an Interface?

I have an Interface lets say ISendOut which I've inherited two different classes from it
for example TransferViaSerialPort and TransferViaWirelessModule (I mean implement this Interface in these two classes). How can I design my software to both giving the ability to the user to choose (IN THE UI) between the methods of sending his/her data out via SerialPort or WirelessModule and not violate the OCP? Because if I want to have a "Switch Case" or an "If/Else" statement I will Violate the OCP.
You need to use the Factory Pattern. And to make the Factory Pattern dynamic you can use Reflection and to show the Types of your Classes in the UI which are Implemented from ISendOut you can use Custom Attributes or other methods like using a Dictionary.
[System.AttributeUsage(System.AttributeTargets.Class)]
public class DisplayNameAttribute : Attribute
{
public DisplayNameAttribute(string displayName)
{
DisplayName = displayName;
}
public string DisplayName { get; set; }
}
public interface ISendOut
{
void Send(string data);
}
[DisplayName("Wireless")]
public class WirelessSendOut : ISendOut
{
public void Send(string data)
{
MessageBox.Show("data sent through wireless.");
}
}
[DisplayName("Serial")]
public class SerialSendOut : ISendOut
{
public void Send(string data)
{
MessageBox.Show("data sent through serial port.");
}
}
public static class SendOutFactory
{
public static ISendOut CreateSendOut(string typeName)
{
var types = Assembly.GetExecutingAssembly().GetTypes();
var sendOutType = types.First(x => (typeof(ISendOut)).IsAssignableFrom(x) && x.Name == typeName);
return (ISendOut) Activator.CreateInstance(sendOutType);
}
}
public static class SendOutDiscovery
{
public static IEnumerable<NameType> Discover()
{
var types = Assembly.GetExecutingAssembly().GetTypes();
var sendOutTypes = types.Where(x => x != typeof(ISendOut) && (typeof(ISendOut)).IsAssignableFrom(x));
return sendOutTypes.Select(type => GetNameType(type)).ToList();
}
private static NameType GetNameType(Type type)
{
var nameType = new NameType
{
DisplayName = GetDisplayName(type),
TypeName = type.Name
};
return nameType;
}
private static string GetDisplayName(Type type)
{
return ((DisplayNameAttribute)type.GetCustomAttributes(typeof (DisplayNameAttribute), false).First()).DisplayName;
}
}
public class NameType //for binding in UI
{
public string DisplayName { get; set; }
public string TypeName { get; set; }
}
public class SendOutViewModel //sample using in wpf (window contains a combobox)
{
public SendOutViewModel()
{
SendTypes = new ObservableCollection<NameType>(SendOutDiscovery.Discover());
}
public NameType SelectedSendType { get; set; } //bind to selected item in combobox
public ObservableCollection<NameType> SendTypes { get; private set; } //bind to item source of combo
public string Data { get; set; } //data to be sent
public void Send()
{
ISendOut sendOut = SendOutFactory.CreateSendOut(SelectedSendType.TypeName);
sendOut.Send(Data);
}
}
Later I add UsbSendOut without modifying existing code (so not Breaking the OCP)
[DisplayName("Usb")]
public class UsbSendOut : ISendOut
{
public void Send(string data)
{
MessageBox.Show("data sent through usb.");
}
}
You pass your implementation of ISendOut as a parameter, e.g. to a constructor, and let C#'s dynamic dispatch do the "switch case", as you've put it.
That's why interfaces are so useful: you have an indirection and can do dependency injection to meet OCP.
Create a UserConfiguredCommunicationModule class (favor composition over inheritance)
public class UserConfiguredCommunicationModule : ISendOut
{
public UserConfiguredUserModule(SerialPort serial, WirelessModule wireless)
{}
public void Send(string data)
{
if (UserIdentity.Current.PrefersSerial)
serial.Send(data);
else
wireless.Send(data);
}
}
Using that implementation will prevent you from breaking OCP (although the class itself violates OCP, but that can easily be fixed by using a factory in it).
Update
you know what's wrong with that? I want to give the ability to the user to choose the method of Sending Out the Data in the UI. Now imagine that we will have much more methods of Sending Out i.e. Sending Out Via Infrared or ... so by letting the user choose between different methods, I have to have an if statement in my UI which it will violate the OCP. Because every new type of Sending Out will force me to have new if/else condition
My approach move the violation of OCP into one class only, instead of every single place where the ISendOut interface is used.
I also mentioned factory, in which I mean the factory pattern (neither abstract factory or factory method). You can use it to map between configuration strings and the concrete classes and use that factory inside of UserConfiguredCommunicationModule to create the proper ISendOut implementation.
You can also use service locator pattern within the UserConfiguredCommunicationModule to resolve the correct implementation.
That point is no matter what you choose, you need a UserConfiguredCommunicationModule similar class to encapsulate the selection process.
Check out the strategy pattern
https://en.wikipedia.org/wiki/Strategy_pattern
http://www.dofactory.com/Patterns/PatternStrategy.aspx#_self1

How to I implement this Base/Derived class structure?

I'm writing a C# application that reads in a source code file of language X, and populates a data structure with the classes, methods etc. that appear in the source file.
After that, using this data structure I just populated, I can call any of these three functions:
GenerateCS()
GenerateJava()
GenerateCPP()
Basically, it ports language X to either of those three languages.
My question is, how can I structure this such that I have one class GenerateCode which functions as a base class and the other generate functions derive from it?
I suppose the particular syntax details of each language would have to reside within the derived classes itself, but what stuff could I abstract to the superclass?
What about:
public enum Language
{
CS,
Java,
CPP
}
public class CS: BaseClass { }
public class Java: BaseClass { }
public class Cpp: BaseClass { }
public class BaseClass
{
public abstract BaseClass ConvertTo(Language lang);
}
or
public class BaseClass
{
public abstract FromClass(BaseClass class, Language lang);
}
I would recommend that you start with a structure like this:
public class MetaCode
{
private IList<Fields> fields;
private IList<Properties> properties;
private IList<Methods> methods;
public IList<Fields> Fields
{
get { return this.fields; }
}
public IList<Properties> Properties
{
get { return this.properties; }
}
public IList<Methods> Methods
{
get { return this.methods; }
}
// etc...
}
public interface ISourceReader
{
MetaCode ReadCode(string sourceCode);
}
public interface ISourceWriter
{
string WriteCode(MetaCode metaCode);
}
public class CodeConverter
{
private ISourceReader reader;
private ISourceWriter writer;
public CodeConverter(ISourceReader reader, ISourceWriter writer)
{
this.reader = reader;
this.writer = writer;
}
public string Convert(string sourceCode)
{
MetaCode metaCode = this.reader.ReadCode(sourceCode);
return this.writer.WriteCode(metaCode);
}
}
This is just pseudo-code, but you could probably make your interfaces follow the StreamReader/StreamWriter pattern that appears frequently in the .NET framework.
The interfaces allow neat extension points where you can add new source and destination programming languages to your application. The best thing about this approach is that the CodeConverter class knows nothing about the different programming languages that exist. New ones can be added or removed and it doesn't need to change. Other people can even create new language readers / writers and use them without touching your code / compiled assembly.
To be honest, thinking about this, I dont think there is much functionality that you can abstract out to a base class. The details of each language is so specific that a base class is difficult to do correctly. In any case, I'd always recommend starting out with the interfaces because then you can always create an implementation no matter how obscure / different a programming language is.
Perhaps you could create several "helper" base classes that contain some abstracted functionality for the different general styles of programming language there are:
public abstract class CLikeSourceReader : ISourceReader
{
public MetaCode ReadCode(string sourceCode)
{
// etc..
}
// etc..
}
public abstract class VisualBasicLikeSourceReader : ISourceReader
{
public MetaCode ReadCode(string sourceCode)
{
// etc..
}
// etc..
}
public abstract class AssemblyLanguageLikeSourceReader : ISourceReader
{
public MetaCode ReadCode(string sourceCode)
{
// etc..
}
// etc..
}
This way, when adding a new language you have the option to inherit from one of these pre-existing base classes, with the option to fall back on the interfaces if none of the them are suitable.

Implement common behaviour in alternative to abstract base classes?

In C#, I have a class hierarchy with a couple of abstract base classes near the top and a fair number of derived classes. A few these concrete classes have some common properties and methods that are implemented identically. It strikes me as wasteful and so one solution might be to implement this common behaviour in another abstract base class.
abstract class Control;
abstract class SquareControl: Control
{
public int SquarishProperty;
public void SquarishMethod();
};
class Window: SquareControl;
class Button: SquareControl;
However, what if several other classes in the hierarchy shared some other behaviour but also share something in common with one of the controls from another base class? Perhaps there are lots of areas of commonality. It would become impractical to model this with abstract base class implementation wouldn't it?
abstract class FlashableControl: Control
{
public int FlashyProperty;
public void FlashMethod();
};
class StatusBar: FlashableControl; // but it's also a bit square too, hmm...
So how do you go about sharing such implementations across classes without using base classes?
I imagine I want to delegate the implementaion of an interface to another class and have that class implement those properties and methods on behalf of the desired classes, so that to the user, the StatusBar and Window appear to support a standard interface, but under the covers it's something else that implements it.
I can visualise aggregating classes that implement this behaviour, but is this appropriate and are there any pitfalls? What are the alternatives?
Thanks
You can use a pattern like this:
public interface ICommonServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
public static class CommonServiceMethods
{
public static void DoSomething(this ICommonServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
All classes that implement ICommonServices now also get some free behavior via the extension method, which depends solely on those features exposed by all ICommonServices implementers. If you need access to base class functionality, you can put that in its own interface and have ICommonServices implement that interface as well. Now you can create 'default' extension functionality for interfaces without having to use multiple base classes.
EDIT
If you want some of these methods to be internal, you can modify the pattern like this:
public class MyObject : IServices
{
public string PublicProperty { get; private set; }
string IServices.SomeProperty { get; set; }
void IServices.SomeMethod(string param)
{
//Do something...
}
}
public interface IPublicServices
{
string PublicProperty { get; }
}
internal interface IServices : IPublicServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
internal static class ServiceMethods
{
public static void DoSomething(this IServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
Basically we're exposing both public and internal interfaces. Note that we implement the internal interface methods explicitly, so that the methods are not available for public consumption (since the public client can't get access to the interface type.) In this case, the helper extension methods are internal, relying on the internal interface, though you could also create public helper methods that rely on the public interface.
You could use 'has-a' instead of 'is-a' and delegate to an internal square control
class Window : Control, ISquareControl
{
private SquareControl square;
public void SquareOperation()
{
square.SquareOperation();
}
}
class SquareControl : Control, ISquareControl
{
public void SquareOperation()
{
// ...
}
}
One way is to use Interfaces and Base Classes.
Flashable would make a good Interface instead of a class.

Categories

Resources