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
Class1andClass2, it’s quite common for an instance of one to hold a reference to an instance of another. For example, if you have aPlayerclass, and the player has aWeapon, define your class like this:Specifically in your case, it looks like you want to update an instance of
Class1from an instance ofClass2. I would suggest that you define a property onClass2that holds the related instance ofClass1, just as in the example above.This is called the Composite Pattern.
Another pattern frequently used to act on an object instance is the Command Pattern.