工厂方法模式实例

工厂方法模式实例

问题描述

在某网络管理软件中,需要为不同的网络协议提供不同的网络连接类,例如针对POP3协议的连接类POP3Connection,针对IMAP协议的连接类IMAPConnection,针对HTTP协议的连接类HTTPConnection等。由于网络连接对象创建的过程较为复杂,需要将其创建过程封装到专门的类中,该软件还支持更多类型的网络协议。

结构图

工厂方法模式实例

编程实现

Connection类

public interface Connection {
    void connect();
}
public class POP3Connection implements Connection{
    @Override
    public void connect() {
        System.out.println("execute POP3 protocol");
    }
}
public class IMAPConnection implements Connection {
    @Override
    public void connect() {
        System.out.println("execute IMAP protocol");
    }
}
public class HTTPConnection implements Connection{
    @Override
    public void connect() {
        System.out.println("execute HTTP connection");
    }
}

工厂类

public interface ConnectionFactory {
    Connection buildConnection();
}
public class POP3ConnectionFactory implements ConnectionFactory{
    @Override
    public Connection buildConnection() {
        return new POP3Connection();
    }
}
public class IMAPConnectionFactory implements ConnectionFactory{
    @Override
    public Connection buildConnection() {
        return new IMAPConnection();
    }
}
public class HTTPConnectionFactory implements ConnectionFactory{
    @Override
    public Connection buildConnection() {
        return new HTTPConnection();
    }
}

客户端

public class Client {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory=new HTTPConnectionFactory();
        Connection connection=connectionFactory.buildConnection();
        connection.connect();
    }
}
上一篇:MongoDB数据库启动失败


下一篇:Centos 下启动mysql 报错: Can't connect to local MySQL server through socket '/var/lib/mysql/my