luke1985
luke1985

Reputation: 2354

A design pattern concerns

I've found something that very much resembles a design pattern. What I'm doing is creating an instance that is injected into multiple classess. It's by far a DI but what makes it distinct is that an instance is fed into multiple depending classess:

var instance = new ClassA();

var dep1 = new DependentFoo(instance);
var dep2 = new DependentBar(instance);

I've found it usefull for 2 example situations for now:

  1. When making a modular code with multiple GUI modules. I feed an instance of current working data into different dependending classes, so for example when a "New file" is clicked the underlying data is cleared

  2. In game development - when there are many different game modes - every needs a current terrain instance - for example two modes: road building mode and trees placement mode need to have the same instance, because they will work on the same data.

I could probably elaborate on this but my question is: is this a named pattern? I know that DI works by putting dependencies into class. But in my case it's going further - using that instance for multiple dependent classes.

Upvotes: 1

Views: 126

Answers (4)

Ilya Palkin
Ilya Palkin

Reputation: 15727

Modern IoC containers know how to handle it.

It is called

  1. Lifestyles in Castle Windsor
  2. Scope in Ninject
  3. Lifetime Managers in Unity

E.g. there is Scoped Lifestyle in Castle Windsor. It ensures that resolved entities will be the same within the scope.

registration:

Container.Register(Component.For<MyScopedComponent>().LifestyleScoped())

usage:

using Castle.MicroKernel.Lifestyle;

using (Container.BeginScope()) //extension method
{
    var one = Container.Resolve<MyScopedComponent>();
    var two = Container.Resolve<MyScopedComponent>();
    Assert.AreSame(one, two);

} // releases the instance

Bound Lifestyle is used in order to make sure that resolved entities will be the same within specific root/graph.

Upvotes: 1

David Osborne
David Osborne

Reputation: 6781

This is not a specific pattern, AFAIK. Providing a shared resource via DI is just an approach or technique. IoC frameworks would call this 'lifestyle' management.

Upvotes: 1

Lie Ryan
Lie Ryan

Reputation: 64827

You might want to check out the Observer pattern or the MVC pattern as these are what you seems to be going towards.

Upvotes: 1

wheaties
wheaties

Reputation: 35970

It's called object composition and isn't a "design pattern" per se but rather a way of structuring code so you cut down on repetition. People that strongly believe in exactly what you're doing expound on the principals of SOLID and DRY. These are good things if you're in an OO world. (They're also a good philosophy if you're in an FP world up, though DI is sometimes frowned upon.)

Upvotes: 1

Related Questions