专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 什么是Java工厂方法设计模式

什么是Java工厂方法设计模式

更新时间:2022-08-09 10:41:16 来源:动力节点 浏览630次

它是一种关于创建对象的创建设计模式。工厂设计模式说定义一个接口(Java接口或抽象类)来创建对象,让子类决定实例化哪个类。接口中的工厂方法允许类将实例化推迟到一个或多个具体子类。由于这些设计模式谈论对象的实例化,因此它属于创建设计模式的范畴。如果我们注意到名称工厂方法,这意味着有一个方法是工厂,一般来说,工厂涉及创建的东西,在这里,一个对象正在被创建。这是创建对象的最佳方法之一,其中对象创建逻辑对客户端隐藏。现在让我们看一下实现。

执行:

在接口内定义工厂方法。

让子类实现上述工厂方法,并决定创建哪个对象。

在 Java 中,构造函数不是多态的,但通过允许子类创建对象,我们将多态行为添加到实例化中。简而言之,我们试图通过让子类决定创建什么来实现伪多态,因此这个工厂方法也称为虚拟构造函数。

让我们尝试用一个实时问题和一些编码练习来实现它。

问题陈述: 考虑我们想要通过电子邮件、短信和推送通知实现通知服务。让我们尝试在工厂方法设计模式的帮助下实现这一点。首先,我们将为此设计一个 UML 类图。

在上面的类图中,我们有一个名为Notification的接口,三个具体的类正在实现 Notification 接口。创建工厂类 NotificationFactory 以获取 Notification 对象。现在让我们进入编码。

创建通知界面

public interface Notification {
    void notifyUser();
}

注意 - 上面的接口也可以创建为抽象类。

创建所有实现类

SMSNotification.java

public class SMSNotification implements Notification { 
    @Override
    public void notifyUser()
    {
        // TODO Auto-generated method stub
        System.out.println("Sending an SMS notification");
    }
}

电子邮件通知.java

public class EmailNotification implements Notification { 
    @Override
    public void notifyUser()
    {
        // TODO Auto-generated method stub
        System.out.println("Sending an e-mail notification");
    }
}

PushNotification.java

public class PushNotification implements Notification {
    @Override
    public void notifyUser()
    {
        // TODO Auto-generated method stub
        System.out.println("Sending a push notification");
    }
}

创建工厂类 NotificationFactory.java 来实例化具体类。

public class NotificationFactory {
	public Notification createNotification(String channel)
	{
		if (channel == null || channel.isEmpty())
			return null;
		switch (channel) {
		case "SMS":
			return new SMSNotification();
		case "EMAIL":
			return new EmailNotification();
		case "PUSH":
			return new PushNotification();
		default:
			throw new IllegalArgumentException("Unknown channel "+channel);
		}
	}
}

现在让我们使用工厂类通过传递一些信息来创建和获取具体类的对象。

public class NotificationService {
    public static void main(String[] args)
    {
        NotificationFactory notificationFactory = new NotificationFactory();
        Notification notification = notificationFactory.createNotification("SMS");
        notification.notifyUser();
    }
}

输出:发送短信通知

实时示例:

这种设计模式在JDK中已经被广泛使用,例如

1. java.util.Calendar、NumberFormat、ResourceBundle的getInstance()方法采用工厂方法设计模式。

2. Java 中的所有包装类,如 Integer、Boolean 等,都使用这种模式来使用 valueOf() 方法评估值。

3. java.nio.charset.Charset.forName()、java.sql.DriverManager#getConnection()、java.net.URL.openConnection()、java.lang.Class.newInstance()、java.lang.Class。 forName() 是使用工厂方法设计模式的一些示例。

以上就是关于“什么是Java工厂方法设计模式”的介绍,大家如果想了解更多相关知识,可以关注一下动力节点的Java在线学习,里面的课程内容从入门到精通,细致全面,很适合没有基础的小伙伴学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>