Reputation: 24789
I have a situation where I must send mail A and sometime I have to send mail B, but there are also situation where I want to send a mail which is consists of a combination of mail A and mail B.
For example mail A has as it's subject 'Subject of mail A'. Mail B's subject is 'This is the subject of mail B'. Now I have the situation where I want this as my subject: 'Subject of mail A / This is the subject of mail B'
How can I achive this using an OO way?
I already have two seperate classes for mailA and mailB.
Upvotes: 3
Views: 75
Reputation: 174279
Assuming you have a base class Mail
- or an interface IMail
- with the two properties Subject
and Body
, you can create a derived class CompositeMail
:
public class CompositeMail : Mail
{
private readonly List<Mail> _mails;
public CompositeMail(params Mail[] mails) : this(mails.AsEnumerable())
{
}
public CompositeMail(IEnumerable<Mail> mails)
{
if(mails == null) throw new ArgumentNullException("mails");
_mails = mails.ToList();
}
public override string Subject
{
get { return string.Join("/", _mails.Select(x => x.Subject)); }
}
public override string Body
{
get
{
return string.Join(Environment.NewLine, _mails.Select(x => x.Body));
}
}
}
This is an abbreviated implementation of the Composite pattern. "Abbreviated", because it doesn't contain methods the add, remove or enumerate the children. If you want to add this functionality, simply make CompositeMail
additionally implement ICollection<Mail>
.
You can instatiate it like this:
var compositeMail = new CompositeMail(mailA, mailB);
You can use this instance anywhere where you use a normal mail, because it derives from the Mail
class you use elsewhere.
Upvotes: 8