Shane Teed
Shane Teed

Reputation: 33

Can I make a class method behave differently in different instances?

I've edited my question with more details below.

This idea may be completely out there, but my example is as follows:

I want to create a Person class, and have a method Act() (most likely from an interface). Every person needs to be able to Act, but each person will Act differently. For example, Bob will cook, Sam will tell a joke, and Kevin will chase the dog.

Is there a way to implement this type of thing, or do I need to create a Person class, and then derive Bob, Sam, and Kevin, and implement the Act method accordingly.

EDIT: To clarify, since this was flagged as being too broad, here is my specific goal.

I am building a little text based game (I am learning the language and I always find games can help because they require a broad range of features). I need to have different Enemies, with each variety needing to Act, but obviously they won't all act the same. They need to check for special conditions, and perform different action based on those conditions.

I really was just wondering if I would sub-class each variety of enemy, or if there was a more practical way to approach this.

As suggested below, a strategy pattern seems like a viable solution, though in the end, it still seems like I would still be creating an Action class, and then sub-classing that and passing it into the enemy class.

Hopefully this clears up my intent a little more. Thank you all for the answers so far. It's already given me something new to look at, which has already been helpful.

Upvotes: 3

Views: 150

Answers (1)

squillman
squillman

Reputation: 13641

If you don't want to subclass something you could do is implement Person so that it takes an Action as a dependency, then execute that action in the Act() method.

public class Person {

   private Action _actAction;

   public Person(Action actAction) {
        _actAction = actAction;
   }

   public void Act() {
       _actAction.Invoke();
   }

}

Upvotes: 3

Related Questions