Java设计模式(工厂模式)

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

        工厂模式用于封装对象的创建过程,使代码更具灵活性和可维护性。它通过定义一个创建对象的接口,由子类决定实例化哪个类。

简单工厂模式

简单工厂模式通过一个工厂类根据输入条件创建不同类型的对象,但不符合开闭原则

interface Product {
    void show();
}

class ProductA implements Product {
    @Override
    public void show() {
        System.out.println("Product A");
    }
}

class ProductB implements Product {
    @Override
    public void show() {
        System.out.println("Product B");
    }
}

class SimpleFactory {
    public static Product createProduct(String type) {
        switch (type) {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            default:
                throw new IllegalArgumentException("Invalid type");
        }
    }
}

// 使用
Product product = SimpleFactory.createProduct("A");
product.show();
 

工厂方法模式

工厂方法模式将对象创建延迟到子类,每个子类负责一种具体产品的创建,符合开闭原则。

interface Product {
    void show();
}

class ProductA implements Product {
    @Override
    public void show() {
        System.out.println("Product A");
    }
}

class ProductB implements Product {
    @Override
    public void show() {
        System.out.println("Product B");
    }
}

interface Factory {
    Product createProduct();
}

class FactoryA implements Factory {
    @Override
    public Product createProduct() {
        return new ProductA();
    }
}

class FactoryB implements Factory {
    @Override
    public Product createProduct() {
        return new ProductB();
    }
}

// 使用
Factory factory = new FactoryA();
Product product = factory.createProduct();
product.show();
 

抽象工厂模式

抽象工厂模式用于创建一系列相关或依赖的对象,无需指定具体类。适合产品族(多个关联产品)的创建。

interface CPU {
    void process();
}

interface RAM {
    void store();
}

class IntelCPU implements CPU {
    @Override
    public void process() {
        System.out.println("Intel CPU processing");
    }
}

class SamsungRAM implements RAM {
    @Override
    public void store() {
        System.out.println("Samsung RAM storing");
    }
}

interface ComputerFactory {
    CPU createCPU();
    RAM createRAM();
}

class HighEndFactory implements ComputerFactory {
    @Override
    public CPU createCPU() {
        return new IntelCPU();
    }
    @Override
    public RAM createRAM() {
        return new SamsungRAM();
    }
}

// 使用
ComputerFactory factory = new HighEndFactory();
CPU cpu = factory.createCPU();
RAM ram = factory.createRAM();
cpu.process();
ram.store();
 

适用场景

  • 简单工厂模式:对象创建逻辑简单,且无需频繁扩展。
  • 工厂方法模式:需要支持多种产品,且可能动态扩展。
  • 抽象工厂模式:需要创建多个关联产品(如不同操作系统下的UI组件)。

通过工厂模式,可以解耦客户端代码与具体类,提升系统的可扩展性和可维护性。

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

相关推荐

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

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

ANGEL CITY 3197

Java设计模式-工厂模式

介绍简单工厂模式,工厂方法模式,抽象工厂模式。

m0_62946761的博客 6566

使用sysbench对Oracle做基准测试(-) 安装篇

sysbench是一款开源的多线程性能测试工具, 可以执行CPU/内存/线程/IO/数据库等方面的性能测试。数据库目前支持MySQL/Oracle/PostgreSQL。

道行尚浅(老道)的博客 7811

Java设计模式——工厂模式

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

weixin_56032340的博客 8632

FlightStream实战:如何用面元法在笔记本电脑上完成无人机气动分析(附NASA案例)

本文详细介绍了如何利用FlightStream面元法在笔记本电脑上高效完成无人机气动分析,包括其核心技术优势、NASA D8案例实战解析及高效工作流建立。FlightStream作为快速CFD分析工具,显著提升了早期设计阶段的迭代速度,适用于概念设计验证和多气动构型比较。

weixin_28363123的博客 261

[HCTF 2018]WarmUp 1学习记录

#[HCTF 2018]WarmUp 1学习笔记 最近做了做ctf,觉得真的很有趣,后悔当初没早点做,不过之前的学习也让我得到了不少经验基础,废话不多说,这次ctf虽然基本上靠了网上的大佬们(因为比较菜),但自己也做了些思考,应该对新手也比较友好吧。 ##1 首先怎么找源码,我承认我确实刚开始不知道在哪找,不过也很快找到了,相信也会有部分新手和我差不多吧 然后下面控制台会有个temp0,然后直接回车 后面我就受到启发,直接在链接后面加上source.php,进行页面跳转,然后就可以开始PHP代码审计了。

weixin_45869407的博客 685

Java设计模式之工厂模式

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

m0_68821222的博客 1015

IDEA系列(四):IDEA导入Maven工程项目并配置Tomcat启动

本片文章主要介绍如何导入一个存在的maven项目并配置Tomcat启动项目,方便自己使用,也分享出来,希望可以帮助到其他人。

低调D树苗的博客 1244

java设计模式二、工厂

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

2301_79028279的博客 1454

MCGS触摸屏Modbus TCP通讯实战:从寄存器写入到字符串处理的完整代码解析

本文详细解析了MCGS触摸屏通过Modbus TCP协议实现寄存器写入和字符串处理的完整代码,涵盖单寄存器写入、多寄存器写入及字符串传输等核心技术。文章还提供了MCGS组态环境中的实战配置步骤和常见问题排查方法,帮助开发者快速掌握工业自动化通讯的关键技术。

study的专栏 758

Windows11安装Ubuntu 20.04.3 LTS双系统(详细过程)

一、基础环境 听说BIOS模式的传统MBR模式和新式UEFI模式,会对安装双系统产生影响。Windows11应该都是UEFI吧,可以按win+r输入msinfo32回车确认查看BIOS模式,我的电脑是UEFI+双硬盘 Ubuntu安装准备 1、 官网下载Ubuntu 20.04.3 LTS镜像iso文件:https://ubuntu.com/download/desktop 2、 下载官网推荐的U盘启动制作工具rufus: https://rufus.ie/ 3、制作启动u盘 插入U盘, 运行 rufu

学习随笔 9万+

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

设计模式之工厂模式

季鸢的博客 1093

使用 Python 构建 Reddit 热帖爬虫:抓取热门讨论帖和评论

在现代互联网中,Reddit 被誉为全球最大、最活跃的讨论平台之一,汇聚了各种主题的帖子、评论和社交互动。因此,抓取 Reddit 上的热门帖子和评论可以为我们提供一个丰富的文本数据源,可以用于情感分析、话题建模、趋势分析等应用。Reddit 提供了官方的 API,可以让开发者获取包括帖子、评论、用户信息等在内的各种数据。我们可以结合上述方法,抓取多个热门帖子,并将每个帖子的标题、作者、发布时间和评论内容保存到一个数据结构中。每个帖子的对象包含了丰富的信息,如标题、内容、发布时间、作者等。

2201_76125261的博客 382

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

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

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

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

尹煜的博客 1506

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

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

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

weixin_28938701的博客 174

深度学习工具包 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中三种常见设计模式:单例模式确保类只有一个实例,分为饿汉式(启动即初始化)和懒汉式(首次访问初始化);工厂模式通过工厂类创建对象,实现创建与使用分离,支持灵活扩展;代理模式通过代理类控制对实际对象的访问,实现权限检查等功能。这些模式各有适用场景,合理运用能提升代码的可维护性和扩展性。文章通过具体代码示例展示了每种模式的实现方式,帮助开发者理解设计模式的核心思想与应用方法。

user340的博客 2521

图解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

青青子衿 189

Java设计模式之《工厂模式》

本文系统介绍了工厂模式在面向对象编程中的应用。主要内容包括:工厂模式的定义,将对象创建过程封装隔离以提高灵活性;三种实现方式(简单工厂模式、工厂方法模式、抽象工厂模式)的特点和适用场景,通过汽车生产示例展示模式演进;各模式的Java代码实现示例及其优缺点分析。文章指出,工厂模式的核心价值在于解耦对象的创建和使用,便于系统扩展,并比较了不同模式的适用条件:简单工厂适用于单一产品,工厂方法适用于产品扩展,抽象工厂适用于配套产品族的创建。

weixin_50055999的博客 1337
上一篇: Java 设计模式(介绍)
下一篇: Springboot 集成apache-camel +mqtt 根据主题处理mqtt消息
Java程序之猿
博客等级 码龄9年 2599粉丝 140原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值