Story
October 1 is the birthday of light snow. Many pursuers want to surprise Xiao Xue on their birthday and express their love. These pursuers racked their brains to send a creative greeting text message for Xiao Xue. It seems that Xiaoxue's birthday must be very happy this year. However, Xiao Xue's mobile phone is quite special and can only accept text messages from the same brand as her mobile phone. What should we do?
These pursuers are worrying about how to send their birthday wishes. In order to live up to the painstaking efforts of these pursuers, kind Xiaoxue provides them with a unified sending method, in addition, different brands of mobile phones can send text messages. In this way, these pursuers no longer have to worry about the failure of light snow to receive well-prepared birthday greetings.
Factory Method Solution
Xiao Xue's practice is exactly the idea of the factory method model:Delay the instantiation of a class to the subclass. Defines a factory class used to create objects, which decides to instantiate a specific class derived from the same abstract class. This mode mainly includes three roles: factory class, abstract class (Interface), and specific class.
The interface is as follows:
Namespace Xiaoxue
{
Public interface iMessage
{
Void sendmessage (Object MSG );
}
}
The factory type is as follows:
Namespace Xiaoxue
{
Public class messagefactory
{
Public static iMessage createmessage (string type)
{
IMessage message = NULL;
Switch (type)
{
Case "Nokia ":
Message = new Nokia ();
Break;
Case "Motorola ":
Message = new Motorola ();
Break;
Case "Sankey ":
Message = new Sankey ();
Break;
}
Return message;
}
}
}
Different mobile phone types are implemented as follows:
Namespace Xiaoxue
{
Public class Nokia: iMessage
{
Public void sendmessage (Object MSG)
{
// Send a Nokia text message;
}
}
Public class MOTOROLA: iMessage
{
Public void sendmessage (Object MSG)
{
// Send a Motorola SMS;
}
}
Public class Sankey: iMessage
{
Public void sendmessage (Object MSG)
{
// Send a Sankey text message;
}
}
}
In this way, these pursuers can easily send birthday greetings to Xiao Xue, such as Nokia mobile phone text messages:
IMessage message = messagefactory. createmessage ("Nokia ");
Message. sendmessage ("Happy Birthday, the longer the light snow, the more beautiful. Like your James ");