-
Notifications
You must be signed in to change notification settings - Fork 7
Mutliple mixins
Composite Oriented Programming strive for decoupling and separation of concerns which is not addressed by Object Oriented.
As a person we have multiple roles/tasks in life.
For example a person could be a developer and a musician.
We will be able to accomplish this decoupling by introducing multiple mixins.
We will define these roles as types and implement each role as mixin.
public interface IDeveloper
{
void Code();
}
public interface IMusician
{
void Play();
}
public interface IPerson : IDeveloper, IMusician
{
}
Now we need to define concrete types that will implement each interface.
IPerson
will serve the role of the composite.
We need to define concrete types only for IDeveloper
and IMusician
, NCop will do the rest and craft the
IPerson
composite.
Let's define the concrete types.
public class CSharpDeveloperMixin : IDeveloper
{
public void Code() {
Console.WriteLine("C# coding");
}
}
public class GuitarPlayerMixin : IMusician
{
public void Play() {
Console.WriteLine("I am playing C# accord with Fender Telecaster");
}
}
We need to order NCop to match between interfaces and implementations using MixinsAttribute
attribute.
[TransientComposite]
[Mixins(typeof(CSharpDeveloperMixin), typeof(GuitarPlayerMixin))]
public interface IPerson : IDeveloper, IMusician
{
}
That's all, we've finished creating the composite type.
Now we need to create a CompositeContainer
which will handle two things:
- Craft the real implementation for
IPerson
in runtime. - Act as a Dependency Injection Container that will resolve our type.
using System;
using NCop.Composite.Framework;
using NCop.Mixins.Framework;
namespace NCop.Samples
{
class Program
{
static void Main(string[] args) {
IPerson person = null;
var container = new CompositeContainer();
container.Configure();
person = container.Resolve<IPerson>();
person.Code();
}
}
}
The expected output should be
"C# coding"
"Playing C# accord with Fender Telecaster"
Your end result of the code should be similar to this:
using System;
using NCop.Composite.Framework;
using NCop.Mixins.Framework;
namespace NCop.Samples
{
[TransientComposite]
[Mixins(typeof(CSharpDeveloperMixin), typeof(GuitarPlayerMixin))]
public interface IPerson : IDeveloper, IMusician
{
}
public interface IDeveloper
{
void Code();
}
public interface IMusician
{
void Play();
}
public class GuitarPlayerMixin : IMusician
{
public void Play() {
Console.WriteLine("Playing C# accord with Fender Telecaster");
}
}
public class CSharpDeveloperMixin : IDeveloper
{
public void Code() {
Console.WriteLine("C# coding");
}
}
class Program
{
static void Main(string[] args) {
IPerson person = null;
var container = new CompositeContainer();
container.Configure();
person = container.Resolve<IPerson>();
person.Code();
person.Play();
}
}
}