3

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.

4
  • Do mailA and mailB have a common interface or base class? Commented Apr 12, 2013 at 11:03
  • At this moment they have a common interface, but I can refactor this if necessarily Commented Apr 12, 2013 at 11:08
  • 1
    Create a + overload for instances of MailA and MailB, than add its properties value and send back the new combined object Commented Apr 12, 2013 at 11:10
  • Martijn, didn't my answer help you? Is something unclear? Please ask if this is the case. Commented Apr 16, 2013 at 8:45

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.