deleyd
asked on
Beginner: combining two nearly identical classes?
How can I combine these two nearly identical classes?
class MyMsgAAA
{
private int msglen = 0;
private byte[] MyMsg = new byte[500];
/*constructor*/
public MyMsgAAA(byte[] ba)
{
//Now build the message
this.add(0x01);
...
add some bytes special to AAA messages
...
//message itself (.add escapes any special bytes)
for (int i = 0; i < ba.Length; i++)
{
this.add(ba[i]);
}
}
/* THE REST HERE IS IDENTICAL */
public void add(byte b)
{
MyMsg[msglen++] = b;
}
//Return message
public byte[] msg
{
get
{
byte[] target = new byte[this.msglen];
Array.Copy(MyMsg, target, msglen);
return target;
}
}
}
class MyMsgBBB
{
private int msglen = 0;
private byte[] MyMsg = new byte[500];
/*constructor*/
public MyMsgBBB(byte[] ba)
{
//Now build the message
this.add(0x01);
...
add some bytes special to BBB messages
...
//message itself (.add escapes any special bytes)
for (int i = 0; i < ba.Length; i++)
{
this.add(ba[i]);
}
}
/* THE REST HERE IS IDENTICAL */
public void add(byte b)
{
MyMsg[msglen++] = b;
}
//Return message
public byte[] msg
{
get
{
byte[] target = new byte[this.msglen];
Array.Copy(MyMsg, target, msglen);
return target;
}
}
}
In general, I want to call
MyMsgXXX(various parameters)
If the parameter types were always different I could just make different constructors for the same class. But what if some messages have the same type of parameter (such as in example above)?
I would say make a common base class which encapsulates the common functionality. You can provide specialized constructors in each child if need be.
ASKER
Example?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
:)