Home » Design Pattern » Factory method

Factory method

作者:

分類:

Factory method

Factory Method Concept

The Factory is a commonly used creational design pattern in programming. Its purpose is to defer the instantiation of objects to the subclasses, meaning that the process of object creation is written in the factory, and users only need to call the factory to create the desired objects.

Factory Method Example

Taking two common industrial communication methods (Ethernet and SerialPort) as examples, suppose there are two controllers, A using network communication and B using SerialPort communication.

How can we integrate them? The following is a commonly used approach: if a third communication method needs to be added in the future, you only need to add the relevant objects and corresponding enumerations, without modifying the core program.

The entire system, including interfaces, will be updated accordingly.

//**************
//* author: cian
//* 20231001
//**************

enum ConnectionTypeEnum
{
    Ethernet,
    SerialPort,
}

interface IConnector 
{
    void Connect();
    void Disconnect();
}

class Ethernet : IConnector { /*Implement*/ }
class SerialPort : IConnector { /*Implement*/ }

static class ConnectorFactory
{
    static IConnector GenConnector(ConnectionTypeEnum type)
    {
        switch(type)
        {
     	    case Ethernet:
                return new Ethernet();
     	    case SerialPort:
                return new SerialPort();
            default:
                throw new NotImplementedException();
        }
    }
}

IConnector myConnector = ConnectorFactory.GenConnector(connType);
myConnector.Connect();
myConnector.Disconnect();

Conclusion

The pattern can have various implementations, but the basic concept remains consistent. Many design patterns, such as the Abstract Factory, stem from this concept.

By applying the pattern to the actual program architecture, one can write elegant and well-structured code.

References

cian Avatar

留言

Leave a Reply

Your email address will not be published. Required fields are marked *