Java设计模式 - 工厂模式

JAVA编程【设计模式之工厂模式】 工厂模式(Factory Pattern)是一种创建对象的设计模式,它通过隐藏实例化逻辑,使代码更加松耦合、易维护。工厂模式属于创建型设计模式,主要用于解耦对象的创建过程。 阅读详情

什么是工厂模式?

工厂模式是一种创建对象的设计模式,它把对象的创建过程封装起来,客户端只需要告诉工厂"我要什么",工厂就会返回相应的对象。

就像餐厅点餐:

  • 你告诉服务员"我要一份宫保鸡丁"
  • 厨师在后厨制作(你不需要知道怎么做)
  • 服务员把做好的菜端给你

主要解决什么问题?

工厂模式主要解决以下问题:

  1. 对象创建复杂:对象的创建需要复杂逻辑(如读取配置、依赖组装)
  2. 解耦客户端:客户端代码不依赖具体类,只依赖抽象接口
  3. 集中管理:统一管理对象的创建和生命周期
  4. 避免重复代码:将创建逻辑集中在一处,避免到处写new

何时使用工厂模式?

当你遇到以下场景时,考虑使用工厂模式:

  • 需要根据不同条件创建不同对象(如不同支付方式)
  • 对象的创建过程复杂(需要初始化、设置参数等)
  • 希望隐藏创建细节(客户端不关心对象怎么来的)
  • 需要统一管理对象的创建(如连接池、线程池)

工厂模式的优点

  1. 解耦:客户端和具体实现类解耦
  2. 可扩展:新增产品只需添加新类,符合开闭原则
  3. 复用:创建逻辑可以复用
  4. 统一管理:对象的创建和配置集中管理
  5. 测试友好:可以轻松替换mock对象

工厂模式的缺点

  1. 增加类数量:每增加一个产品可能需要增加一个工厂类
  2. 复杂度提升:引入抽象层次,增加理解难度
  3. 过度设计:简单场景用工厂反而复杂

代码示例:通知系统

让我们用一个通知系统的例子来演示工厂模式的三种变体。

1. 简单工厂模式(静态工厂)

// 产品接口
interface Notification {
    void send(String message);
}

// 具体产品:邮件通知
class EmailNotification implements Notification {
    @Override
    public void send(String message) {
        System.out.println("发送邮件: " + message);
        // 实际的邮件发送逻辑
    }
}

// 具体产品:短信通知
class SMSNotification implements Notification {
    @Override
    public void send(String message) {
        System.out.println("发送短信: " + message);
        // 实际的短信发送逻辑
    }
}

// 具体产品:微信通知
class WeChatNotification implements Notification {
    @Override
    public void send(String message) {
        System.out.println("发送微信: " + message);
        // 实际的微信发送逻辑
    }
}

// 简单工厂
class NotificationFactory {
    public static Notification createNotification(String type) {
        switch (type.toLowerCase()) {
            case "email":
                return new EmailNotification();
            case "sms":
                return new SMSNotification();
            case "wechat":
                return new WeChatNotification();
            default:
                throw new IllegalArgumentException("未知的通知类型: " + type);
        }
    }
}

// 客户端使用
public class SimpleFactoryDemo {
    public static void main(String[] args) {
        // 从配置文件读取通知类型
        String notificationType = "email";
        
        Notification notification = NotificationFactory.createNotification(notificationType);
        notification.send("Hello, World!");
        
        // 输出:发送邮件: Hello, World!
    }
}

特点:一个工厂生产所有产品,简单直接,但扩展性差。

2. 工厂方法模式

// 抽象工厂接口
interface NotificationFactory {
    Notification createNotification();
}

// 具体工厂:邮件工厂
class EmailNotificationFactory implements NotificationFactory {
    @Override
    public Notification createNotification() {
        // 可以在这里进行复杂的初始化
        System.out.println("初始化邮件服务...");
        // 配置SMTP服务器、认证信息等
        return new EmailNotification();
    }
}

// 具体工厂:短信工厂
class SMSNotificationFactory implements NotificationFactory {
    @Override
    public Notification createNotification() {
        System.out.println("初始化短信服务...");
        // 配置短信网关、模板等
        return new SMSNotification();
    }
}

// 具体工厂:微信工厂
class WeChatNotificationFactory implements NotificationFactory {
    @Override
    public Notification createNotification() {
        System.out.println("初始化微信服务...");
        // 配置微信API、密钥等
        return new WeChatNotification();
    }
}

// 客户端使用
public class FactoryMethodDemo {
    public static void main(String[] args) {
        // 根据配置选择工厂
        NotificationFactory factory = getNotificationFactory("sms");
        Notification notification = factory.createNotification();
        notification.send("Hello, Factory Method!");
    }
    
    private static NotificationFactory getNotificationFactory(String type) {
        switch (type.toLowerCase()) {
            case "email":
                return new EmailNotificationFactory();
            case "sms":
                return new SMSNotificationFactory();
            case "wechat":
                return new WeChatNotificationFactory();
            default:
                throw new IllegalArgumentException("未知的通知类型");
        }
    }
}

特点:每个产品有自己的工厂,符合开闭原则,扩展性好。

3. 抽象工厂模式(产品族)

// 抽象产品1:通知发送器
interface NotificationSender {
    void send(String message);
}

// 抽象产品2:通知记录器
interface NotificationLogger {
    void log(String message);
}

// 抽象产品3:通知模板
interface NotificationTemplate {
    String format(String message);
}

// 邮件产品族
class EmailSender implements NotificationSender {
    @Override
    public void send(String message) {
        System.out.println("邮件发送: " + message);
    }
}

class EmailLogger implements NotificationLogger {
    @Override
    public void log(String message) {
        System.out.println("邮件日志: " + message);
    }
}

class EmailTemplate implements NotificationTemplate {
    @Override
    public String format(String message) {
        return "[邮件] " + message;
    }
}

// 短信产品族
class SMSSender implements NotificationSender {
    @Override
    public void send(String message) {
        System.out.println("短信发送: " + message);
    }
}

class SMSLogger implements NotificationLogger {
    @Override
    public void log(String message) {
        System.out.println("短信日志: " + message);
    }
}

class SMSTemplate implements NotificationTemplate {
    @Override
    public String format(String message) {
        return "[短信] " + message;
    }
}

// 抽象工厂:通知产品族工厂
interface NotificationFactoryV2 {
    NotificationSender createSender();
    NotificationLogger createLogger();
    NotificationTemplate createTemplate();
}

// 邮件工厂
class EmailNotificationFactoryV2 implements NotificationFactoryV2 {
    @Override
    public NotificationSender createSender() {
        return new EmailSender();
    }
    
    @Override
    public NotificationLogger createLogger() {
        return new EmailLogger();
    }
    
    @Override
    public NotificationTemplate createTemplate() {
        return new EmailTemplate();
    }
}

// 短信工厂
class SMSNotificationFactoryV2 implements NotificationFactoryV2 {
    @Override
    public NotificationSender createSender() {
        return new SMSSender();
    }
    
    @Override
    public NotificationLogger createLogger() {
        return new SMSLogger();
    }
    
    @Override
    public NotificationTemplate createTemplate() {
        return new SMSTemplate();
    }
}

// 客户端使用
public class AbstractFactoryDemo {
    public static void main(String[] args) {
        // 使用邮件产品族
        NotificationFactoryV2 emailFactory = new EmailNotificationFactoryV2();
        
        NotificationSender emailSender = emailFactory.createSender();
        NotificationLogger emailLogger = emailFactory.createLogger();
        NotificationTemplate emailTemplate = emailFactory.createTemplate();
        
        String message = "Hello, World!";
        String formattedMessage = emailTemplate.format(message);
        emailSender.send(formattedMessage);
        emailLogger.log(formattedMessage);
        
        System.out.println("---");
        
        // 使用短信产品族
        NotificationFactoryV2 smsFactory = new SMSNotificationFactoryV2();
        
        NotificationSender smsSender = smsFactory.createSender();
        NotificationLogger smsLogger = smsFactory.createLogger();
        NotificationTemplate smsTemplate = smsFactory.createTemplate();
        
        formattedMessage = smsTemplate.format(message);
        smsSender.send(formattedMessage);
        smsLogger.log(formattedMessage);
    }
}

特点:生产一系列相关的产品(产品族),保证产品之间的兼容性。

4. 使用反射的通用工厂

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

// 通用工厂(使用反射)
class GenericFactory {
    private static final Map<String, Class<? extends Notification>> registry = new HashMap<>();
    
    // 注册产品类
    public static void register(String type, Class<? extends Notification> clazz) {
        registry.put(type.toLowerCase(), clazz);
    }
    
    // 创建产品
    public static Notification create(String type, Object... args) {
        try {
            Class<? extends Notification> clazz = registry.get(type.toLowerCase());
            if (clazz == null) {
                throw new IllegalArgumentException("未注册的类型: " + type);
            }
            
            // 根据参数选择构造函数
            if (args.length == 0) {
                return clazz.getDeclaredConstructor().newInstance();
            } else {
                // 处理带参数的构造函数
                Class<?>[] paramTypes = new Class<?>[args.length];
                for (int i = 0; i < args.length; i++) {
                    paramTypes[i] = args[i].getClass();
                }
                Constructor<? extends Notification> constructor = clazz.getConstructor(paramTypes);
                return constructor.newInstance(args);
            }
        } catch (Exception e) {
            throw new RuntimeException("创建对象失败", e);
        }
    }
}

// 新增产品:钉钉通知
class DingTalkNotification implements Notification {
    private String webhook;
    
    public DingTalkNotification() {
        this.webhook = "default-webhook";
    }
    
    public DingTalkNotification(String webhook) {
        this.webhook = webhook;
    }
    
    @Override
    public void send(String message) {
        System.out.println("发送钉钉消息到 " + webhook + ": " + message);
    }
}

// 客户端使用
public class GenericFactoryDemo {
    public static void main(String[] args) {
        // 注册产品
        GenericFactory.register("email", EmailNotification.class);
        GenericFactory.register("sms", SMSNotification.class);
        GenericFactory.register("dingtalk", DingTalkNotification.class);
        
        // 无参创建
        Notification email = GenericFactory.create("email");
        email.send("无参创建");
        
        // 有参创建
        Notification dingtalk = GenericFactory.create("dingtalk", "https://oapi.dingtalk.com/robot/send");
        dingtalk.send("有参创建");
    }
}

5. Spring框架中的工厂模式

import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

// Spring FactoryBean示例
@Component
class NotificationFactoryBean implements FactoryBean<Notification> {
    private String type;
    private String config;
    
    // 通过配置文件注入
    public void setType(String type) {
        this.type = type;
    }
    
    public void setConfig(String config) {
        this.config = config;
    }
    
    @Override
    public Notification getObject() throws Exception {
        switch (type) {
            case "email":
                EmailNotification email = new EmailNotification();
                // 根据config配置邮件
                return email;
            case "sms":
                SMSNotification sms = new SMSNotification();
                // 根据config配置短信
                return sms;
            default:
                throw new IllegalArgumentException("未知类型");
        }
    }
    
    @Override
    public Class<?> getObjectType() {
        return Notification.class;
    }
    
    @Override
    public boolean isSingleton() {
        return true; // 单例模式
    }
}

实际应用场景

工厂模式在Java中的经典应用:

  1. Spring IoC容器:BeanFactory根据配置创建对象

    BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
    UserService userService = factory.getBean(UserService.class);
    
  2. 日志框架:LoggerFactory创建Logger

    Logger logger = LoggerFactory.getLogger(MyClass.class);
    
  3. JDBC:DriverManager创建Connection

    Connection conn = DriverManager.getConnection(url, username, password);
    
  4. 线程池:Executors创建线程池

    ExecutorService executor = Executors.newFixedThreadPool(10);
    
  5. Java标准库:Calendar.getInstance()、NumberFormat.getInstance()

三种工厂模式的对比

模式特点适用场景开闭原则
简单工厂一个工厂生产所有产品产品种类少且固定❌ 违反
工厂方法每个产品有自己的工厂产品可能扩展✅ 符合
抽象工厂生产产品族(多个相关产品)需要配套产品✅ 符合

选择建议

  • 产品种类少且稳定 → 简单工厂
  • 产品种类可能扩展 → 工厂方法
  • 需要配套产品 → 抽象工厂
  • 对象创建简单 → 直接new就好,别过度设计

总结

工厂模式的核心思想是:将对象的创建和使用分离。它就像现实生活中的工厂一样,你只需要告诉工厂你要什么,工厂负责生产,你只管使用。

关键点:

  • 简单工厂:一个工厂生产所有产品
  • 工厂方法:每个产品有自己的工厂
  • 抽象工厂:生产一系列相关产品
Java设计模式之简单工厂模式 所以,干脆在模块内部新建一个类,在这个类里面来创建接口,然后把创建的接口返回给具体调用者,这样,外部应用就只需根据这个类来获取相应的接口对象,然后就可以操作接口定义的方法了。虽然说简单工厂的方法大多是用来创建接口的,但是仔细分析你会发现,真正能实现功能的是具体的实现类,这些实现类是已经做好的,并不是真的要靠简单工厂来创建出来的,简单工程的方法无外乎就是:实现了选择一个合适的实现类来使用。私有化简单工厂的构造方法,使用静态方法来创建接口,也就不能通过写简单工厂类的子类来改变创建接口的方法行为了。 阅读详情

相关推荐

java设计模式之工厂设计模式——Factory Pattern

设计模式故事会:https://blog.csdn.net/weixin_40205234/article/details/90664824 工厂模式 工厂模式(Factory Pattern)是java中最常见的设计模式之一,该类型属于创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口指向新创建的对象。 1.简...

ANGEL CITY 3201

设计模式创建型——工厂模式

工程模式是通过工厂获取一个一个的新对象。定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。

tszc95的博客 5697

VLM,VLA,VLN的区别与联系

VLM 提供了理解世界的“眼睛和大脑”,VLN 赋予了这个智能体在空间中“移动的双腿”,而 VLA 则进一步赋予了它“灵巧的双手”来改变世界。三者共同构成了一个完整具身智能体的核心能力模块。

l0409044222的博客 1320

设计模式第3讲——工厂模式(Factory)

工厂模式是一种创建型设计模式。一、什么是工厂模式 二、工厂分类 三、应用场景3.1 生活场景3.2 java场景 四、 工厂模式实现4.0 代码结构4.1 传统模式4.2 简单工厂模式4.3 方法工厂模式4.4 抽象工厂模式五、总结5.1 简单工厂模式5.2 方法工厂模式5.3 抽象工厂

让~学习~成为一种习惯(橡 皮 人の技术博客) 1万+

TC397 EB配置ADC软件触发:从零实现周期采样与中断处理

本文详细介绍了如何在Infineon AURIX TC397芯片上使用EB Tresos工具配置ADC软件触发,实现周期采样与中断处理。通过硬件连接、EB模块配置、代码初始化及数据处理的全流程解析,帮助开发者快速掌握ADC软件触发技术,提升嵌入式系统开发效率。

root9的博客 234

本地如何安装midscene.js运行环境

手把手教你本地安装midscene.js运行环境

实践助梦想成长 2616

23种设计模式——工厂模式

文章目录23种设计模式——工厂模式1、工厂模式概述2、简单工厂模式2.1、简单工厂模式的优缺点2.2、简单工厂模式的结构2.3、简单工厂模式的实现3、工厂方法模式3.1、工厂方法模式的优缺点3.2、工厂方法模式的结构3.3、工厂方法模式的实现4、抽象工厂模式4.1、抽象工厂模式概述4.2、抽象工厂模式结构4.3、抽象工厂模式实现 23种设计模式——工厂模式 1、工厂模式概述 工厂模式的定义:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。这满足创建型模式中所要

万里顾一程的博客 1万+

Unity ECS 之 Entitas 的简单介绍,插件下载、导入,和简单使用(一篇文入门搞懂ECS是什么)

Unity ECS 之 Entitas 的简单介绍,插件下载、导入,和简单使用(一篇文入门搞懂ECS是什么) 目录 Unity ECS 之 Entitas 的简单介绍,插件下载、导入,和简单使用(一篇文入门搞懂ECS是什么) 一、简单介绍 二、一些专有项简介 Entity Context Group Collector Matcher System Feature 三、注意实现 四、ECS 的下载 Github 上下载 Unity Asset Store 中下载 U...

仙魁XAN 7782

Java设计模式-工厂模式

1.概述 需求:设计一个咖啡店点餐系统。 设计一个咖啡类(Coffee),并定义其两个子类(美式咖啡【AmericanCoffee】和拿铁咖啡【LatteCoffee】);再设计一个咖啡店类(CoffeeStore),咖啡店具有点咖啡的功能。 具体类的设计如下: 在java中,万物皆对象,这些对象都需要创建,如果创建的时候直接new该对象,就会对该对象耦合严重(CoffeeStore对AmericanCoffr),假如我们要更换对象,所有new对象的地方都需要修改一遍,这显然违背了软件设计的开闭原则。如果

Java硬件工程师的博客 4046

RK3588开发板量产前必做:24小时DDR压力测试到底在测什么?(附ArmSoM-W3测试脚本解析)

本文深入解析RK3588开发板量产前的24小时DDR压力测试,揭示其核心价值与技术原理。通过memtester、stressapptest和变频测试的组合使用,全面验证DDR内存稳定性。特别介绍ArmSoM-W3测试脚本的创新设计,包括并行测试架构和异常熔断机制,为开发者提供可靠的量产测试方案。

weixin_30325487的博客 456

Android 13.0 framework默认沉浸式导航栏功能实现

​ 在13.0的系统rom定制化开发中,在实现导航栏的某些定制化开发中,在某些产品需要实现沉浸式导航栏,就是需要app 能全屏显示同样也能显示导航栏,接下来就来分析下相关的功能实现 ​

安卓兼职framework和app工程师的博客 473

最通俗易懂的讲解工厂模式

该模式用来封装和管理类的创建,终极目的是为了解耦,实现创建者和调用者的分离。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。工厂模式可以细分为三种:简单工厂模式工厂方法模式抽象工厂模式.........

weixin_43757333的博客 2万+

TensorRT的安装:一步一步教会你如何安装TensorRT

TensorRT(Tensor Runtime)是由NVIDIA开发的一个用于深度学习推理(inference)优化的库,它可以在NVIDIA的GPU上加速神经网络模型的推理过程,从而提高模型的性能和效率。安装完成后,需要将CUDA的安装路径添加到系统环境变量中,以便系统能够找到CUDA的库文件。根据你安装的CUDA版本,将CUDNN的库文件复制到CUDA的安装目录中。要使用TensorRT,首先需要安装NVIDIA的CUDA和cuDNN库,并根据NVIDIA官方文档安装TensorRT。

Science prince的博客 2373

Java设计模式——工厂模式

本文对设计模式中工厂模式进行思想和原理的讲解,引用实际例子来方便理解。

weixin_56032340的博客 8633

【大模型】从0到1:DeepSeek + Coze API调用全攻略,企业,开发个人专属AI智能体使用详解,小白也能轻松上手

本文介绍了如何通过API将Coze智能体集成到自有系统中的完整步骤:1)获取API token和个人工作空间的space_id;2)通过GET请求获取bot_id;3)使用POST发起对话请求,需包含bot_id、user_id和问题内容;4)通过两次API调用异步获取响应消息。文章还解释了Coze采用异步处理机制的原因,并预告了下期将讲解Java调用Coze接口的实现方法。整个过程需要使用API工具进行调试,确保了系统集成的可行性。

qq_27246521的博客 827

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Java设计模式之工厂模式

工厂模式是Java中最常用的设计模式之一,属于创建型模式。

m0_68821222的博客 1015

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java设计模式二、工厂

工厂方法模式是一种常用的创建型设计模式,它通过将对象的创建过程封装在工厂类中,实现了创建与使用的分离。这种模式不仅提高了代码的复用性,还增强了系统的灵活性和可扩展性。本文将详细介绍工厂方法模式的三种形式:简单工厂模式、工厂方法模式和抽象工厂模式,并通过Java代码示例帮助你深入理解。工厂方法模式(Factory Method Pattern)由父类提供一个创建对象的方法,允许子类决定实例化对象的类型。这种模式的核心思想是解耦- 将对象的创建过程与使用过程分离,使得代码更容易维护和扩展。

2301_79028279的博客 1454

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Java设计模式之工厂模式详解

设计模式之工厂模式

季鸢的博客 1093

【Java开发】设计模式 02:工厂模式

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

尹煜的博客 1507

java设计模式工厂模式_Java中的工厂设计模式

java设计模式工厂模式Welcome to the Factory Design Pattern in Java tutorial. Factory Pattern is one of the Creational Design pattern and it’s widely used in JDK as well as frameworks like Spring and Struts. 欢迎...

从零开始的教程世界 349

java设计模式 工厂,Java 设计模式——工厂模式

image前言最近在复习java设计模式中的工厂模式。本来有一点小小的理解。感觉都写的不错,就是有点太零散了,最后还是决定自己手写一把,加深印象。顺便做个总结,以后复习起来也方便许多。一、简介目前从网上了解工厂模式大体分为简单工厂、工厂方法、抽象工厂等三种模式。工厂方法模式也可称为工厂模式,与抽象模式都是属于GOF23种设计模式中的一员。可以大概理解为:简单工厂进阶变成了工厂方法,然后再进阶成了抽...

weixin_28938701的博客 174

图解Java设计模式之工厂模式

图解Java设计模式之工厂模式简单工厂模式 简单工厂模式 看一个具体的需求 看一个披萨的项目 :要便于披萨种类的扩展,要便于维护 1)披萨的种类很多(比如GreekPizz、CheesePizz等) 2)披萨的制作有prepare、bake、cut、box 3)完成披萨店订购功能。 ...

不一样的花朵的博客 632

java设计模式之工厂设计模式

java设计模式之工厂设计模式 传统模式 看一个具体的需求 看一个披萨的项目:要便于披萨种类的扩展,要便于维护 1.披萨的种类很多(比如 GreekPizz、CheesePizz 等) 2.披萨的制作有 prepare,bake, cut, box 3.完成披萨店订购功能。 使用传统的方式来完成 首先创建一个pizza类 package com.wxit.factory.simplefactory; /** * @Author wj **/ //将Pizza类做成抽象 public abstract

青青子衿 192
上一篇: Tomcat 的安装(配置详细教程)
下一篇: Snipaste截图软件安装、详细图文教程(附下载链接)
Moon_VA
博客等级 码龄3年 279粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址