Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
An application I'm working on processes Work Items. Depending on the state of a work item there are a number of actions available. "Complete" "Cancel" "Reassign" etc...
To provide the functionality for the actions I currently have an interface that looks something like this...
public interface IActionProvider{
public void Complete(WorkItem workItem);
public void Cancel (WorkItem workItem);
public void Reassign(WorkItem workItem);
}
Then based on other details of the work item I have concrete implementations of the interface. Just for example...
public class NormalActionProvider :IActionProvider
{
...
}
and
public class UrgentActionProvider : IActionProvider
{
....
}
The problem is, if I want to add a new action, say... "Delegate" I have to update the interface which of course has effects on all of the implementations.
Does this violate the Open/Close Principle? Can you recommend a design pattern or refactor that may help me here?
Looks like command pattern would be suitable. You can modify/add more commands. The command classes are decoupled from the main program.
public interface IActionProvider{
public void execute(WorkItem item,ActionType actionType);
}
ActionType represents Complete,Cancel & so on. You can keep adding more action types & plugin appropriate command classes.
You could always add a Decorator to the IActionProvider interface (follow the Decorator design pattern).
It depends on what you really are trying to accomplish with your IActionProvider. If you really want to make it so that every implementation must be able to perform all of the actions that you consider to be important, then that should be a part of the interface that they implement. Interfaces work best if they are well-planned ahead of time so they don't have to change continually.
But it sounds like you don't necessarily want all actions to be implemented by all providers. I'd need to know more details to be able to give good advice, but one example would be to have the providers initialize themselves against a kind of event Bus. They could subscribe to those events that they care about, and perform actions only for the events that make sense for the specific implementation.
"Depending on the state of the workitem", brings the State Design Pattern
One way or another, you'll have to refactor you interface and eventually break client contracts.
If i have understood your problem correctly, then you have a WorkItemProcessor whose state changes depending
on the WorkItem Sent to it.
Therefore your WorkItemProcessor becomes
// Context
public class WorkItemProcessor
{
public IState CurrentState { get; set; }
public WorkItemProcessor(IState initialState)
{
CurrentState = initialState;
}
public void Process(WorkItem workItem)
{
CurrentState.Handle(this, workItem);
}
}
Then we define multiple states that the WorkItemProcessor could potentially be in
// State Contract
public interface IState
{
void Handle(WorkItemProcessor processor, WorkItem item);
}
// State One
public class CompleteState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CompletenessConditionHoldsTrue ? (IState) this : new CancelState();
}
}
// State Two
public class CancelState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CancelConditionHoldsTrue ? (IState) this : new CompleteState();
}
}
Assuming your WorkItem Looks like
// Request
public class WorkItem
{
public bool CompletenessConditionHoldsTrue { get; set; }
public bool CancelConditionHoldsTrue { get; set; }
}
To put it all together
static void Main()
{
// Setup context in a state
WorkItemProcessor processor = new WorkItemProcessor(new CancelState());
var workItem1 = new WorkItem { CompletenessConditionHoldsTrue = true };
var workItem2 = new WorkItem { CancelConditionHoldsTrue = true };
// Issue requests, which toggles state
processor.Process(workItem1);
processor.Process(workItem2);
Console.Read();
}
Hope this gets you closer. Cheers.
I would also choose the command pattern. As an enhancement, you can combine it with the abstract factory method, so you can have a factory class for each command class, and all those factories implement a common factory interface.
For example:
// C#
public interface ICommand { void Execute(); }
public interface ICommandFactory { ICommand Create(); }
public class CommandFactoryManager
{
private IDictionary<string, ICommandFactory> factories;
public CommandFactoryManager()
{
factories = new Dictionary<string, ICommandFactory>();
}
public void RegisterCommandFactory(string name, ICommandFactory factory)
{
factories[name] = factory;
}
// ...
}
This way, you can register new command factories dynamically. For example, you can load a DLL at runtime and fetch all the classes that implement the ICommandFactory interface using reflection, and you have a simple plugin system.
Related
I just started to learn Decorator Design Pattern, unfortunately i had to go through various refrences to understand the Decorator pattern in a better manner which led me in great confusion. so, as far as my understanding is concern, i believe this is a decorator pattern
interface IComponent
{
void Operation();
}
class Component : IComponent
{
public void Operation()
{
Console.WriteLine("I am walking ");
}
}
class DecoratorA : IComponent
{
IComponent component;
public DecoratorA(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("in the rain");
}
}
class DecoratorB : IComponent
{
IComponent component;
public DecoratorB(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("with an umbrella");
}
}
class Client
{
static void Main()
{
IComponent component = new Component();
component.Operation();
DecoratorA decoratorA = new DecoratorA(new Component());
component.Operation();
DecoratorB decoratorB = new DecoratorB(new Component());
component.Operation();
Console.Read();
}
}
But can the below code also be Decorator Pattern?
class Photo
{
public void Draw()
{
Console.WriteLine("draw a photo");
}
}
class BorderedPhoto : Photo
{
public void drawBorder()
{
Console.WriteLine("draw a border photo");
}
}
class FramePhoto : BorderedPhoto
{
public void frame()
{
Console.WriteLine("frame the photo");
}
}
class Client
{
static void Main()
{
Photo p = new Photo();
p.Draw();
BorderedPhoto b = new BorderedPhoto();
b.Draw();
b.drawBorder();
FramePhoto f = new FramePhoto();
f.Draw();
f.drawBorder();
f.frame();
}
}
My Understanding
From the second example given by me, we can call all the three methods, but from the first example i wont be able to get access to all the three methods by creating a single object.
It should be a comment, but I have too many words.
For example, you have an object and interface, like Repository : IRepository.
public interface IRepository
{
void SaveStuff();
}
public class Repository : IRepository
{
public void SaveStuff()
{
// save stuff
}
}
and client, which probably was written by someone else
class RepoClient
{
public void DoSomething(IRepository repo)
{
//...
repo.SaveStuff();
}
}
And once you decided, that ALL calls to repository should be logged. But you have a problem: the Repository class is from an external library and you don't want to change that code. So you need to extend the Repository's behavior that you use. You write RepositoryLogDecorator : IRepository, and inside on each method do the logging, like
public class RepositoryLogDecorator : IRepository
{
public IRepository _inner;
public RepositoryLogDecorator(IRepository inner)
{
_inner = inner;
}
public void SaveStuff()
{
// log enter to method
try
{
_inner.SaveStuff();
}
catch(Exception ex)
{
// log exception
}
// log exit to method
}
}
So, before you could use client as
var client = new RepoClient();
client.DoSomething(new Repository());
but now you can use
var client = new RepoClient();
client.DoSomething(new RepositoryLogDecorator(new Repository()));
Note, that this is a very simple example. In real projects, where object created primary with DI container, you will be able to use decorator by changing some config.
So, decorator is used to extend functionality of object without changing object or client.
Another benefit of decorator: your decorator does not depend on Repository implementation. Only depends from an interface IRepository. Why this is an advantage? If somehow you decide to write you own implementation of IRepository
public class MyAwesomeRepository : IRepository
{
public void SaveStuff()
{
// save stuff, but AWESOME!
}
}
you will be able to automatically decorate this with decorator, which already exist
var client = new RepoClient();
client.DoSomethig(new RepositoryLogDecorator(new MyAwesomeRepository()));
Want to see example from real software? (just as sample, code is ugly, I know) => go here
There is this PatternCraft series on Youtube that explains Design Patterns with Starcraft, you should check the video about Decorators here.
In the video above the author gives an example with a Marine and WeaponUpgrade.
In the game you will have a Marine and then you can upgrade its weapon:
marine = new WeaponUpgrade(marine);
Note that you still have a marine there, it is not a new unit, it is the same unit with things that modifies its attributes.
public class MarineWeaponUpgrade : IMarine
{
private IMarine marine;
public MarineWeaponUpgrade(IMarine marine)
{
this.marine = marine;
}
public int Damage
{
get { return this.marine.Damage + 1; } // here
set { this.marine.Damage = value; }
}
}
You do that by creating a class that implements the same interface as your unit and access your unit properties to modify values.
There is a Kata on CodeWars challenging you to complete the Weapon and Armor decorators for a marine.
Per GOF page Decorator desing pattern:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
In your second example you are using inheritance to extend behaviour of a class, I believe this is technically not a Decorator design pattern.
The decorator pattern allows you to add a specific behavior to an individual object of a given type without affecting other instances of that same type.
In your second example, which is normal inheritance, all instances of the class inherit the modified behavior.
The second example is not a decorate pattern, since an essential ingredient to decorator pattern is that the object accepts one of its kind and possibly enhance it.
An instances of this in the first example is
public DecoratorA(IComponent c)
{
component = c;
}
Also, the goal of the decorator pattern is to create "one" object, then decorate it by passing it through different filters or decorators.
Hence the line
DecoratorA decoratorA = new DecoratorA(new Component());
Should be
DecoratorA decoratorA = new DecoratorA(component );
I want to integrate my application with X number of external systems. The integration with each external system will have same kind of actions but will be handled in a separate classes.
Hence the aim to define an interface that will make sure all integration classes conform to certain actions. e.g.
public interface IOrderIntegration
{
//I want to define the ImportOrder action here, so that all future integrations conform
}
However each external system has its own closed SDK (cannot be edited) that needs to be referenced. e.g
public class EbayOrderIntegration : IOrderIntegration
{
void ImportOrder(Ebay.SDK.Order order)
{
//Logic to import Ebay's order
}
}
public class AmazonOrderIntegration : IOrderIntegration
{
void ImportOrder(Amazon.SDK.Order order)
{
//Logic to import Amazon's order
}
}
Is there a way to still use an interface in this case to ensure all integrations perform a certain action? Or perhaps another pattern ?
This is where generics come intp play:
public interface IOrderIntegration<T>
{
void ImportOrder(T order);
}
public class EbayOrderIntegration : IOrderIntegration<Ebay.SDK.Order order>
{
void ImportOrder(Ebay.SDK.Order order order)
{
// ...
}
}
Another way than HimBromBeere's answer (great answer by the way !). Note that this can only work if you can abstract at the order level:
public class OrderIntegration
{
public void ImportOrder(IOrder order)
{
// Only possible if you can abstract all the logic into IOrder
}
}
public interface IOrder
{
// Abstract here the order logic
}
public class EbayOrder : IOrder
{
public EbayOrder(Ebay.SDK.Order order)
{ .. }
}
public class AmazonOrder : IOrder
{
public AmazonOrder(Amazon.SDK.Order order)
{ .. }
}
The choice between HimBromBeere's anwser and mine will depend on where you want to (and can!) abstract your different providers and how you want to use your API.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am using command pattern in C#.
There is a class that contains some properties named RequiredData.
public class RequiredData
{
public Class1 class1 { get; set; }
public int value1 {get; set;}
}
There is an abstract class BaseCommand and there are some derived classes like command1 , command2 etc.
abstract class BaseCommand : ICommand { }
The commands operate some actions like:
command1.Execute();
command2.Execute();
I want during the whole process to have a shared RequiredData object which can be updated and used from all commands.
For example:
in command1 Execute method to access the value1 like :
RequiredData.Value1 = 5
and then in command2 Execute method to have this value like
var k = RequiredData.Value1 //and be 5..
or RequiredData.Class1.something = "something"
I tried this one in the base class:
abstract class BaseCommand : ICommand
{
//or protected and not private...
public static RequiredData RequiredData = new RequiredData();
}
is this thread-safe?
What changes needed here for a thread-safe solution?
You could solve this by using several methods.
Pass the shared instance into the constructor
Singleton pattern/static could help, but is more restricted.
Reminder is, if you use the class on different thread, you need to care about thread safety.
Normally I avoid a static object that can be readed/writed by multiple threads. I advise you to try to get rid from this.
But... you need to be sure, that the object/reference types are not accessible from the outside.
like:
// you could create the locking in this class, but the class1 property is a
// reference type, so just locking in the property is not enought, it
// goes wrong when the Class1 has properties itself. (then these will be
// altered outside the lock..
// I choose to wrap the whole object and only returning value types
public class RequiredData
{
public Class1 class1 { get; set; }
public int value1 {get; set;}
}
abstract class BaseCommand : ICommand
{
// protected.. should not be accessable from the outside..!
protected static RequiredData RequiredData = new RequiredData();
public int GetValue()
{
lock(RequiredData)
return RequiredData.value1;
}
public void SetValue(int value)
{
lock(RequiredData)
RequiredData.value1 = value;
}
// or you could wrap this in a property
public int Value
{
get { return lock(RequiredData) RequiredData.value1; }
set { lock(RequiredData) RequiredData.value1 = value; }
}
public string GetSomething()
{
// try to avoid returning reference types, but the can be referenced from outside the object.
lock(RequiredData)
return RequiredData.Class1.something;
}
}
So the locking should be inside the BaseCommand. And the BaseCommand should be responsible for communicating with the RequiredData. (so no other object could have a reference to the RequiredData)
Like I said: Multithreading / static read/writer = playing with fire.
If you have many readers/writers you should have a look at the ReaderWriterLock(Slim). Because multiple threads can read simultaneously and only one writer is active.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Let's say I have the following inheritance tree:
______ Object______
/ \
Food Material
/ \ / \
Egg Carrot Box Axe
Expressed like this in C#
class Object { ... }
class Food : Object { ... }
class OfficeMaterial : Object{ ... }
class Box : OfficeMaterial { ... }
class Spoon : OfficeMaterial { ... }
class Egg : Food { ... }
class Carrot : Food { ... }
And now I want to share the functionality only between the class Box and Egg, for instance:
bool opened = true;
public void Open() { open = true; }
public void Close() { open = false; }
public bool IsOpen() { return opened; }
This is a short example, but it could be something much longer.
What would be the proper way to do it? If I use inheritance, other classes like Carrot and Axe will get it, which is something I do not wish.
UPDATE
Many people mention Composition. Could someone show me how that would work in the example I presented?
You have a few options:
Use interfaces
Ex:
public interface IOpenable
{
void Open();
void Close();
bool IsOpen();
}
Then any class that needs the openable/closable behavior can implement the interface accordingly.
Favor composition over inheritance and compose your objects out of other objects that implement the desired behavior.
Why not use an interface? IOpenable?
interface IOpenable {
void Open();
void Close();
bool IsOpen();
}
When I think about the similarities between Egg and Box that are not properties shared by Carrot and Axe I think first about the fact that they contain something.
Egg and Box have Contents which can be exposed, hidden, added, removed, etc.
Notice the language here - Egg and Box have Contents. The word have (or has) is an indicator that an object representing the Contents of another object should be used as a composition element.
An Egg is a type of Food. An Egg has Contents which are a Yolk and an EggWhite.
A Box is a type of OfficeMaterial. A Box has Contents which are OfficeSupplies.
I could write something like this:
public class Food : Object
{
public void Eat() { }
}
public class OfficeMaterial : Object { }
public class Contents : Object
{
bool _visible = false;
List<Object> _things = new List<Object>();
public int Count { get { return _things.Count; } }
public bool IsOpen { get { return _visible; } }
public void Expose()
{
_visible = true;
}
public void Hide()
{
_visible = false;
}
public void Add(object thing)
{
_things.Add(thing);
}
public bool Remove(object thing)
{
return _things.Remove(thing);
}
}
public class Box : OfficeMaterial
{
public Contents BoxContents = new Contents();
}
public class Egg : Food
{
public Contents EggContents = new Contents();
}
Which would further allow me to:
void PlaceEggsInBox(int numEggs, Box box)
{
box.BoxContents.Expose();
if (box.BoxContents.AreVisible)
{
int eggsInBox = box.BoxContents.Things.Count(thing => thing is Egg);
for (int i = 0; i < numEggs - eggsInBox; i++)
{
box.BoxContents.Add(new Egg());
}
}
}
And then I might like to
void EatAllEggsInBox(Box box)
{
box.BoxContents.Expose();
foreach (Egg egg in box.BoxContents.Things.Where(thing => thing is Egg))
{
box.BoxContents.Remove(egg);
egg.EggContents.Expose();
if (egg.EggContents.AreVisible) egg.Eat();
}
}
The Eat() method is a method of the Food class. The Expose() method is a method of the Contents class, not the Food class or the OfficeMaterials class, nor of the Egg nor Box classes.
That's effectively multiple inheritance, which C# doesn't support other than through interfaces.
An option is to create an interface without the Open method (otherwise you'll have to implement it, so this is only for typing purposes) then implement a static extension methods in a static class alongside your interface.
public Interface IOpenable { }
public static class IOpenableExtensions {
public static Open(this IOpenable obj){
// work on any concrete implementation of IOpenable
}
}
Usage:
var box = new Box; // Box implements IOpenable
var egg = new Egg; // Egg implements IOpenable
box.Open();
egg.Open();
This pattern may work well when the actual inheritance reflect a core structure or organization while the interfaces provide common "behaviors" shared by certain objects. A class may implement one or more of such interfaces.
C# 8 default interface implementation might make this pattern more common.
In practice, you often end up needing to cast your objects to the interface when working with functions that deal with your base classes.
public IEnumerable<Food> GetFoods(){ ... }
public void HandleFood() {
for(var food in GetFoods()) {
if(food is IOpenable openableFood){
openableFood.Open();
}
}
}
Finally, note that this is not true multiple inheritance as you cannot inherit/override the extension methods themselves through a hierarchy of interfaces. If you have IOpenableFood inherit IOpenable with both an Open() extension method, you can't call base() in the derived one, and you'll have to choose which extension method to use explicitly. Best to avoid this altogether.
var egg = new Egg(); // Egg inherits both IOpenable and IOpenableFood
egg.Open(); // Error: Ambiguous method
IOpenableFoodExtensions.Open(egg); // OK, call that method
IOpenableExtensions.Open(egg); // OK, call other method
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am making a game that has several classes and each one do some kind of specific task.
I am completely new to OOP and I was wondering what I should do to make my class instances communicate between each other without recurring to static classes, methods and properties, which seems like an awful thing to do.
I am self-taught programmer, and I realize I do a lot of bad practices. So far I managed to make this work making both classes static but I wanted to know what I should do to make my code as good as possible.
Also, it would be nice if you could recommend me some resources/books/articles so I can read more about this topic (communcation between instances).
Here is some piece of code so you understand what I am talking about.
class Program
{
static void Main(string[] args)
{
Class1 instance1 = new Class1();
Class2 instance2 = new Class2();
// infinite loop
while (true)
{
instance1.UpdateMethod(someValue);
instance2.UpdateMethod();
}
}
}
class Class1
{
int Property;
UpdateMethod(int argument)
{
Property += argument;
if(Property == 3000)
{
// I should change the state of instance2
}
}
}
class Class2
{
UpdateMethod()
{
if(Time.GetTime() == SomeTime)
{
// here I want to change the state of instance1
}
}
}
For an overview of common design patterns, I recommend
http://en.wikipedia.org/wiki/Category:Software_design_patterns
If there is a natural relationship between Class1 and Class2, it's quite common for an instance of one to hold a reference to an instance of another. For example, if you have a Player class, and the player has a Weapon, define your class like this:
public class Player
{
public Weapon Weapon { get; set; }
// Other properties
}
Specifically in your case, it looks like you want to update an instance of Class1 from an instance of Class2. I would suggest that you define a property on Class2 that holds the related instance of Class1, just as in the example above.
This is called the Composite Pattern.
In software engineering, the composite pattern is a partitioning
design pattern. The composite pattern describes that a group of
objects are to be treated in the same way as a single instance of an
object. The intent of a composite is to "compose" objects into tree
structures to represent part-whole hierarchies. Implementing the
composite pattern lets clients treat individual objects and
compositions uniformly.
Another pattern frequently used to act on an object instance is the Command Pattern.
In object-oriented programming, the command pattern is a design
pattern in which an object is used to represent and encapsulate all
the information needed to call a method at a later time. This
information includes the method name, the object that owns the method
and values for the method parameters. Three terms always associated
with the command pattern are client, invoker and receiver. The client
instantiates the command object and provides the information required
to call the method at a later time. The invoker decides when the
method should be called. The receiver is an instance of the class that
contains the method's code. Using command objects makes it easier to
construct general components that need to delegate, sequence or
execute method calls at a time of their choosing without the need to
know the owner of the method or the method parameters.
I would suggest you two links and the content their is free to read
http://msdn.microsoft.com/en-us/library/dd460654.aspx
A bit more on patterns with better details is http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep
and final one from uncle bob good explanation on OOD Principles http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
If you need to change the state of an object from another class, you need a reference to it. Common ways to do this are through the constructor:
public class Class2
{
private readonly Class1 instance;
public Class2(Class1 instance)
{
this.instance = instance;
}
public void UpdateMethod()
{
if(VisualStyleElement.TaskbarClock.Time.GetTime() == SomeTime)
{
// here I want to change the state of instance1
this.instance.SomeProperty = "Some Value";
}
}
}
or through a parameter passed into the method
public class Class2
{
public void UpdateMethod(Class1 instance)
{
if (VisualStyleElement.TaskbarClock.Time.GetTime() == SomeTime)
{
// here I want to change the state of instance1
instance.SomeProperty = "Some Value";
}
}
}
In the first case you would call it like this:
Class2 instance2 = new Class2(instance1);
instance2.UpdateMethod();
And in the second case you would call it like this:
Class2 instance2 = new Class2();
instance2.UpdateMethod(instance1);
Be most welcome to the world of OOP!
One important thing to understand is the notion of inheritance. Inheritance regards to what is. A Child is a Person, and a Mother is a person.
Please, take a look at this model:
public class Person
{
protected string Name;
public string WhatsYourName()
{
return this.Name;
}
}
public class Mother: Person
{
public Mother(string personName)
{
this.Name = personName;
}
}
public class Child : Person
{
public Mother MyMother { get; set; }
public Child(string personName)
{
this.Name = personName;
}
public string WhoAreYou()
{
return string.Format("My name is {0} and my mom is {1}", this.Name, this.MyMother.WhatsYourName());
}
}
Now, how do objects talk to each others? There are plenty of ways to achieve this, but it all comes to a simple concept: references.
When you create an object (x = new ...) you are creating a new instance, and you have its reference.
Now, look at this:
static void Main(string[] args)
{
Mother mary = new Mother("Mary");
Child bobby = new Child("Bobby");
bobby.MyMother = mary;
Console.WriteLine(bobby.WhoAreYou());
Console.ReadLine();
}
See when we are setting Bobby's mother? We are passing its object reference.
Please, take a look at this code, I believe it can help.
Further on, I'd strongly recommend you to read about design patterns.
Maybe starting here: http://www.dofactory.com/Patterns/Patterns.aspx/
Hope this helps.
It all depends on what Class1 and Class2 are and if they need to be coupled or not.
If they do unrelated things and do not need to know about each other, you can use events to communicate changes between them:
class Program
{
static void Main(string[] args)
{
Class1 instance1 = new Class1();
Class2 instance2 = new Class2();
instance1.CriticalValueReached += instance2.DoSomething;
instance2.TimeoutElapsed += instance1.DoSomething;
// infinite loop
while (true)
{
instance1.UpdateMethod(someValue);
instance2.UpdateMethod();
}
}
}
class Class1
{
int Property;
public event Action CriticalValueReached;
public UpdateMethod(int argument)
{
Property += argument;
if (Property == 3000)
RaiseCriticalValueReached();
}
public void DoSomething()
{
// Whatever...
}
private void RaiseCriticalValueReached()
{
var handler = CriticalValueReached;
if (handler != null)
handler();
}
}
class Class2
{
public event Action TimeoutElapsed;
public UpdateMethod()
{
if (Time.GetTime() == SomeTime)
RaiseTimeoutElapsed();
}
public void DoSomething()
{
// ...
}
private void RaiseTimeoutElapsed()
{
var handler = TimeoutElapsed;
if (handler != null)
handler();
}
}