i have the following problem.
The 1st step is to implement a program, which follows a specific protocol on startup.
Therefore, functions as onInit, onConfigRequest, etc. will be necessary.
(These are triggered e.g. by incoming message on a TCP Port)
My goal is to generate a class for example abstract one, which has abstract functions as onInit(), etc.
A programmer should just inherit from this base class and should merely override these abstract functions of the base class.
The rest as of the protocol e.g. should be simply handled in the background (using the code of the base class) and should not need to appear in the programmers code.
What is the correct design strategy for such tasks? and how do I deal with, that the static main method is not inheritable? What are the key-tags for this problem? (I have problem searching for a solution since I lack clear statements on this problem)
Goal is to create some sort of library/class, which - included in ones code - results in executables following the protocol.
EDIT (new explanation):
Okay let me try to explain more detailled:
In this case programs should be clients within a client server architecture.
We have a client server connection via TCP/IP. Each program needs to follow a specific protocol upon program start:
As soon as my program starts and gets connected to the server it will receive an Init Message (TcpClient), when this happens it should trigger the function onInit().
(Should this be implemented by an event system?) After onInit() a acknowledgement message should be sent to the server. Afterwards there are some other steps as e.g. a config message from the server which triggers an onConfig and so on. Let's concentrate on the onInit function.
The idea is, that onInit (and onConfig and so on) should be the only functions the programmer should edit while the overall protocol messaging is hidden for him.
Therefore, I thought using an abstract class with the abstract methods onInit(), onConfig() in it should be the right thing. The static Main class I would like to hide, since within it e.g. there will be some part which connects to the tcp port, which reacts on the Init Message and which will call the onInit function.
2 problems here:
1. the static main class cant be inherited, isn it?
2. I cannot call abstract functions from the main class in the abstract master class.
Let me give an Pseudo-example for my ideas:
public abstract class MasterClass
{
static void Main(string[] args){
1. open TCP connection
2. waiting for Init Message from server
3. onInit();
4. Send Acknowledgement, that Init Routine has ended successfully
5. waiting for Config message from server
6.....
}
public abstract void onInit();
public abstract void onConfig();
}
I hope you get the idea now!
The programmer should afterwards inherit from this masterclass and merely need to edit the functions onInit and so on.
Is this way possible? How?
What else do you recommend for solving this?
EDIT:
The strategy ideo provided below is a good one! Check out my comment on that.
Take a look at this, Strategy design pattern, it may help. A short code example below:
class MainClass {
static void Main(string[] args) {
// Where ProcessingStrategy is your abstract class.
// SpecificProcessingStrategy is someone else's implementation.
//
ProcessingStrategy strategy = new SpecificProcessingStrategy();
// Processor is implemented and provided by you and calls the appropriate methods on the
// ProcessingStrategy..
//
Processor processor = new Processor( strategy );
processor.Process();
}
}
If you wanted to provide the Main also, then take a look at having the name of the concrete ProcessingStrategy (SpecificProcessingStrategy in this example) passed in on the command line and load it dynamically (I'm not sure how to do this in C# but I'm sure many examples on the web).
What you are describing is the Template design pattern. Your abstract client contains the protocol details, and delegates to subclasses via protected template/hook methods to allow a conceret client to customize the behavior.
// In your provided library
public abstract class Client
{
public void Run()
{
OpenConnection();
WaitForInitMsg();
OnInit(); // notify subclass
SendInitAckMsg();
WaitForConfigMsg();
OnConfig(); // notify subclass
SendConfigAckMsg();
// etc, etc
}
protected abstract void OnInit() {}
protected abstract void OnConfig() {}
}
// customer/client uses the functionality like this
public class ConsoleClient : Client
{
protected void OnInit()
{
Console.WriteLine("Initialized");
}
protected void OnConfig()
{
Console.WriteLine("Configured");
}
}
public class MainClass
{
static void Main(string[] args)
{
ConsoleClient client = new ConsoleClient();
client.Run();
}
}
The customer never has access to any internals of your Clinet object that you don't explicitly expose.
Well, you are already made a good decision in choosinhg abstract class. Good in it is that you can define abstract methods which consumer (who inherited from it) must override, and have also "normal" methods with code in it. In this way you create a constrains for derived type to implement several set of the functions and plus, provide it with a common set of the functions that any derived type will have by default.
Related
Introduction
I have a public abstract class, with an abstract method, which I want to call from a worker thread.
When the method is called, the respective instance should be locked down in order to prevent state changes during calculation.
I only want to work with the abstract class, as the implementation of the inheritors is done by third parties.
public abstract class MyClass
{
public abstract MyResult GetData();
}
The problem
My library is used by third parties, I have to assume that they know nothing about the internal implementation of the library.
I don't want to force them to study the documentation of my class, before they are able to implement their own inheritor as I consider this bad form.
My approach
My first idea was to add a protected lock object to the class and lock on it when calling the method.
However, in order for this to be useful, the third party would have to lock on it as well, and thus know about it.
As I don't want to force the third party to know about the internals, I don't like this option.
public abstract class MyClass
{
protected readonly object myLock = new object();
public MyResult GetData()
{
MyResult result;
lock(myLock)
{
result = GetDataInternal();
}
return result;
}
protected abstract MyResult GetDataInternal();
}
Background
I'm working on a data pipeline, which runs on a separate thread.
This pipeline requests data in a specific format and processes it in the background.
Providing the data can take some time and the provided data relies on properties of the objects.
In this case, its a preparation pipeline for 3D models.
The question
How can I lock a whole object without knowing its implementation?
If there is no such way, then is there an agreed upon pattern or something like that for this problem?
My library is used by third parties, I have to assume that they know nothing about the internal implementation of the library.
(..)
When the method is called, the respective instance should be locked down in order to prevent state changes during calculation.
I think that the best way is to .. make them know, and make sure they know that they are responsible for it. You can easily make it intuitive without (much) documentation.
Consider changing your abstract class to something like:
public interface ILockable
{
void FreezeDataForCalculations();
void ThawAfterCalculations();
}
public abstract class MyBaseClass<T> where T:ILockable
{
public abstract T GetData();
}
Usage:
public class MyThingie : MyBaseClass<TheActualData>
{
}
public class TheActualData : ILockable
{
public string Foo {get;set;}
public void FreezeDataForCalculations() { ...???...}
public void ThawAfterCalculations() { ....???.... }
}
Now, you effectively ensured that:
whoever wants to implement it, has to provide his own type, that implements extra interface
whoever implementa that extra interface will notice this two methods, and they will at least think "wtf", and will either understand immediatelly, or will try consulting the documentation
you do no locking for the data, creator of the class is responsible for it
implementor now can choose whever to actually implement freeze/thaw pair, or leave them empty and simply write their own code to not modify the data in the meantime
your code now has to call 'Freeze' and 'Thaw' appropriatelly, and can assume the implementor did what he was expected to
On the contrary, if you can't assume that he did was he was expected to, then change API of your library and don't allow user-defined types, and restrict the API to only your own types that you can ensure that will play nice.
I'm trying to get into the habit of coding to an interface rather than an implementation and whilst in most cases I can see the reasoning there are a few where I struggle.
Take this really simple example:
public interface IAuditLog
{
void AddLog(string log);
}
public class AuditLog : IAuditLog
{
public void AddLog(string log)
{
//implementation
}
}
To call the audit log class:
public partial class AuditLogPage : System.Web.UI.Page
{
protected void btnAddLog_Click(object sender, EventArgs e)
{
IAuditLog objAuditLog = new AuditLog();
objAuditLog.AddLog("test log");
}
}
I still have to use AuditLog when instantiating, so what's the point? If the AddLog method signature changes i'm still going to have to go through all my pages that use it and amend the code. Am I missing the point?
Thanks for any help in advance,
Wilky.
In the example if you switched out FileAuditLogger() with DatabaseAuditLogger() or EventLogAuditLogger() you can switch implementations without having to rewrite your code.
Typically you'd use an IoC container (Autofac, StructureMap, Unity, etc.) to automatically wire up the object instantiation. So instead of calling new AuditLog() you would call IoC.Container.Resolve<IAuditLog>()
Let me know if you'd like more information.
Let imagine that there there are two AuditLog classes
class AuditLogToDatabase : IAuditLog // writes to database
and another is
class AuditLogToFile : IAuditLog // writes to file
like
protected void btnAddLog_Click(object sender, EventArgs e)
{
IAuditLog objAuditLog = AuditLogFactory.GetAuditLog();
objAuditLog.AddLog("test log");
}
now you can inject any class based on some configuration at run time without changing the actual implementation
This doesn't necessarily mean that you have to actually use a C# interface. An interface in OOP terms is the publicly visible façade of an API. It's a contract and externally visible results of operations should be specified. How exactly it works beneath the surface should be irrelevant so that you can swap out the implementation at any time.
Of course, in that regard an interface is a method of being able to use different implementations, but so is an abstract base class or even a non-abstract class others can derive from.
But more to the exact point of your question: Of course, when instantiating a class its type must be known, but you don't necessarily have to create the class instance there. You could set an IAuditLog from the outside or get it via a factory class, etc. where you wouldn't know, at that exact point in the code, what exact type you're getting (except that it's compatible with IAuditLog).
This is actually useful when you create the AuditLog instance from a method say like a Factory method and you have more than one AuditLogXXX classes derived from the IAuditLog interface.
So, instead of using this code:
IAuditLog objAuditLog = new AuditLog();
You would actually use this code when you program to an interface:
IAuditLog objAuditLog = LogFactory.GetAuditLog(); //This call is programmed to an interface
where GetAuditLog() is an interface typed method defined on the LogFactory class as below:
class LogFactory
{
public IAuditLog GetAuditLog() // This method is programmed to an interface
{
//Some logic to make a choice to return appropriate AuditLogXXX instance from the factory
}
}
I have a question concerning holding common code in a base class and having the derived class call it, even though the derived class's trigger method has been dispatched from the base. So, base->derived->base type call stack.
Is the following look OK, or does it smell? I have numbered the flow steps...
public abstract class LayerSuperType
{
public void DoSomething() // 1) Initial call from client
{
ImplementThis(); // 2) Polymorphic dispatch
}
protected abstract void ImplementThis();
protected void SomeCommonMethodToSaveOnDuplication(string key) // 4)
{
Configuration config = GetConfiguration(key);
}
}
public class DerivedOne : LayerSuperType
{
protected virtual void ImplementThis() // 2)
{
SomeCommonMethodToSaveOnDuplication("whatever"); // 3) Call method in base
}
}
public class DerivedTwo : LayerSuperType
{
protected virtual void ImplementThis() // 2)
{
SomeCommonMethodToSaveOnDuplication("something else"); // 3) Call method in base
}
}
That looks absolutely fine. Perfect example of why you'd use an abstract class over an interface. It's a bit like a strategy pattern and I have used this fairly regularly and successfully.
Make sure that what the class doing is still dealing with one 'concern' though, only doing one task. If your base class does repository access but the objects are representing documents, don't put the functionality in the base class, use a separate repository pattern/object.
Looks like a very simplified Template Method Pattern where your sub-classes do some specific kinds of things at the right points in the implementation of your algorithm, but the overall flow is directed by a method on the base class. You've also provided some services to your sub-classes in the form of base class methods; that's ok too as long as you're good as far as SOLID goes.
Why not public abstract void DoSomething() and forget about ImplementThis() altogether?
The only reason I can see to leave ImplementThis() is if you want to maintain a consistent interface with DoSomething() which later on down the road will allow the signature of ImplementThis() to change without a breaking change to callers.
I agree that you should maintain a single concern with the class's responsibility but from an overall OOP perspective this looks fine to me. I've done similar on many occasions.
It does smell a little that SomeCommonMethodToSaveOnDuplication is being called in two different ways. It seems to be doing two unrelated things. Why not have two methods?
I am a developer who works primarily with embedded devices (programmed with C and assembly). My C# and OOP knowledge is very limited (although I can fake my way through it when necessary). I have five devices that interface with a PC via USB. The PC does some calculations and sends a result to the device. The same calculations are performed for each device, but the calculations are done differently. For each device, I have a C# Windows Forms application that does some work and sends data back and forth to the device. Currently, I'm trying to get the five different applications merged into one so we can easily make changes, add new devices easily, and have a standard user interface. My problem is that I don't exactly know the best way to do it since I don't know which device will be used until run time. I'm trying to avoid a bunch of if statements and I would like to be able to put each device in a separate file. Here is some psudo-code of what I'm talking about.
class Device //This is what EVERY device can do
{
...
DoWork1();
DoWork2();
DoWork3();
...
}
class Device1
{
...
DoWork1(); //This is how the work is done for this device
DoWork2();
DoWork3();
...
}
class Device2
{
...
DoWork1(); //This is how the work is done for this device (not the same way as Device1)
DoWork2();
DoWork3();
}
public partial class frmMain : Form
{
private (some kind of object or something) CurrentDevice;
public frmMain()
{
...
//Determine what device (could be one of five) is currently being used
CurrentDevice = (which device is currently being used)
//Could be CurrentDevice = new Device1();
}
}
private void Button1_Click()
{
CurrentDevice.DoWork1(); //But this could be Device1.DoWork1() or Device2.DoWork1(), depending on what device is currently being used (which was determined in the frmMain constructor)
}
I'm not really sure, but I'm thinking I could use an interface or maybe inherit the Device1 class for the Device class and override the methods...But I don't know how I would have one generic way of saying CurrentDevice.DoWork1() since CurrentDevice could be Device1 or Device2.
Any ideas would be greatly appreciated. I'm using Visual Studio 2008 with .NET 3.5 on Windows XP SP3 and Windows 7.
I hope I described the problem well enough. If not, or if I didn't mention something that I should, please let me know. I'm new to stackoverflow and C#.
Thank you,
Michael
In your case, you're basically defining a inheritance hierarchy that can either consist of an abstract base class and two derived types or an interface with two implementors of it. For example
public abstract class BaseDevice
{
public abstract void DoWork1();
}
public class Device1 : BaseDevice
{
public override void DoWork1()
{
// provide implementation here
}
}
// also create Device2 : BaseDevice and implement
OR you could utilize an interface definition
public interface IDevice
{
void DoWork1();
}
public class Device1 : IDevice
{
public void DoWork1()
{
// provide implementation
}
}
Which methodology you pick is up to you. You would perhaps favor an abstract base class if, for example, you wanted to define some behavior or properties with implementations that were common throughout the hierarchy. With an abstract class, you can provide implementations. An interface is an empty contract, you cannot provide any common behaviors, only a definition for what behaviors or properties may be present.
Either way you go, you would refer to instances of the more derived type via the abstract or interface base. In this manner, you don't care what the implementing type is, only what it can do (it's methods or properties).
Example:
BaseDevice device1 = new Device1();
BaseDevice device2 = new Device2();
// maybe you have a list?
List<BaseDevice> devices = new List<BaseDevice> { device1, device2 };
foreach (BaseDevice device in devices)
{
device.DoWork1(); // notice you don't care about the actual type, just the behavior
}
I was a little confused at first because in this case the pc does calculations the devices only receive the result. So as I understand it you need different implementations of something on the PC, not the devices themselves.
The real trick here is not about using an interface or inheritance - you already figured that out. The trick is getting the right implementation type, and you use a factory for that part.
But you do have to decide on inheritance vs interface as well.
Use inheritance only if that "something" is truly part of a common, but also meaningful family. Inheritance should have a very strong "is a" element.
OTOH many objects could exist that might do a calculation but that you might not want to make a family. This is where composition is useful. To get that by inheritance you would need to have them share a common base class. Here you can use composition to allow each object to use a common interface to allow the pc to perform the calculation.
I suggest this approach.
You should have a reference to a common, generic interface, IDoCalculation, or some such, that defines a method signature that will be called in the same way for any device.
Next you have to get the device specific implementation for that interface, this is where each device can have a different implementation. Create a class for each device type/implementation.
Now the trick is to get the class you need without having to know what it is. To once again keep the details hidden and make the method calls generic, you can create a parameterized Factory. This factory accepts a parameter that describes what device the pc needs a calculation for. It then interprets that parameter and based on that creates a specific class that implements IDoCalculation. This is returned and you are done.
I leave it to you to figure out how these objects need to be organized into different assemblies...
//Common interface
public interface IDoCalculation
{
//Use whatever method signatures you need
int DoCalculation();
}
public class DeviceImplementation1 : IDoCalculation
{
#region IDoCalculation Members
public int DoCalculation()
{
//Device 1 Specific code goes here
}
#endregion
}
public class DeviceImplementation2 : IDoCalculation
{
#region IDoCalculation Members
public int DoCalculation()
{
//Device 2 Specific code goes here
}
#endregion
}
// A simple factory that does not require a lot of OOP understanding.
public class DeviceCalculationFactory
{
//Return a correct implementor based on the device type passed in
public IDoCalculation GetCalculationImplementationInstance(string devicetype)
{
switch (devicetype)
{
case "Device1":
return new DeviceImplementation1();
case "Device2":
return new DeviceImplementation2();
default:
//TODO ???
return null;
}
}
}
// A simple client that calls the methods and then send the results
public class DeviceManager
{
//To do the calculation, get an implementor for the correct device type from the factory - Presumably the PC knows the device of interest, example "Device1"
public void DoTheCalculationThing(string deviceType)
{
DeviceCalculationFactory factory = new DeviceCalculationFactory();
IDoCalculation calculation = factory.GetCalculationImplementationInstance(deviceType);
int result = calculation.DoCalculation();
// now send the result to the device
}
}
You might be interested in looking at some design patterns for this.
http://www.oodesign.com/
Specifically Abstract Factory and Template Method. I think one of those might be what you're looking for.
http://www.oodesign.com/abstract-factory-pattern.html
http://www.oodesign.com/template-method-pattern.html
As I understand it, you want to be able to have a base class, then inherit the base class functions and define them in subclasses. One of those patterns would probably work for your scenario.
Anthony Pegram's answer is excellent but you may want to take it a step further. It is conceivable that although it appears that all your devices are performing the same tasks you may find that some do not, in fact, perform all the tasks and yet others perform even more.
In such cases you may be tempted to alter the interface to add another DoWork5 or DoWork6 method and simply raise NotImplemented exceptions on types that do not have the particular behaviour.
This is troublesome for many reasons. I would suggest (should you find yourself in this position) to take a look at making your roles explicit. You do this by creating interfaces that represent a particular role (or set of behaviours --- ties in with the interface segregation principle).
So you could have IMediaPlayer with Play, Pause, Rewind and another IMediaRecorder with a Record method. In this way you implement the relevant roles on your concrete classes.
HTH
I have to write 2 text files for a customer. The files contain information from our DB. Our app is being used by many customers and thus not both files will be written for every customer. Some just get the first file and some also the 2nd. The file structure differs from customer to customer, thats why I made an abstract class with an abstract method Write and a specific class for each customer which iverrides the Write method. Thats for the first file which is for all customers, just with different content and structure.
abstract class CustomerWriter
{
//...
abstract Write();
//...
}
Then I have 2 classes which inherit from that. Thats fine I guess. Now for the second file which only needs to be written for some of the customers ... is it a good idea to use the decorator pattern here and decorate the class for the first file? Its not the same base class (CustomerWriter). I am not sure if this is too much for my case, thats why I am asking.
How would I decorate the specific class for the first file?
Thanks :-)
How about you register all allowed file writers based on the customer configuration somewhere and then you execute all the writers which are registered?
Update: You could use an IoC container for that but a simple
public class FileWriterRegistry
{
public void Register(CustomerWriter writer)
{
}
public void WriteAllFiles()
{
... call Write() for each registered writer
}
}
might do.
If you cannot refactor the second writer to share a common base class or interface, you may actually want to use the adapter pattern. You could write an adapter which makes the second writer appear to be a CustomerWriter. That way your clients can use one common base class or interface (even better). Then you can use an IoC container to be able to configure which instance the clients instantiate.
The adapter would look something like this:
public SecondWriterAdapter : CustomerWriter
{
private SecondWriter writerInstance;
public SecondWriterAdapter(SecondWriter writerInstance)
{
this.writerInstance = writerInstance;
}
public override void Write()
{
writerInstance.someExistingWriteMethod();
}
}