java23种常用设计模式之工厂方法模式(Factory Method)2

【Java用法】Java设计模式之(二)工厂模式(Factory Pattern) 本文目录 一、工厂模式的定义 二、工厂模式的分类 三、为什么要用工厂模式 四、工厂模式的代码实现 五、工厂模式之源码 一、工厂模式的定义 先来看一下GOF为工厂模式的定义: “Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses 阅读详情

就举个比较容易理解的例子:人有白、黑、黄三种人,他们都会说会笑,无论什么肤色。类图我就省了,大家有兴趣可以画画。

工厂方法模式:

管你是白的、黑的还是黄的,反正都是人,会说会笑,所以先定义一个人类的接口(Human)

package com.freedom.factory.abstractfactory;

public interface Human {
	
	public void say();
	public void smile();

}
接着定义人种:
package com.freedom.factory.abstractfactory;

public class YellowHuman implements Human{
	
	
	@Override
	public void say() {
		System.out.println("yellow human can say anything!");
		
	}

	@Override
	public void smile() {
		System.out.println("yellow human can smile!");
		
	}

}

package com.freedom.factory.abstractfactory;

public class WhiteHuman implements Human{
    
    
    @Override
    public void say() {
        System.out.println("white human can say anything!");
        
    }

    @Override
    public void smile() {
        System.out.println("white human can smile!");
        
    }

}

package com.freedom.factory.abstractfactory;

public class BlackHuman implements Human{
    
    
    @Override
    public void say() {
        System.out.println("black human can say anything!");
        
    }

    @Override
    public void smile() {
        System.out.println("black human can smile!");
        
    }

}

造人工厂
package com.freedom.factory.abstractfactory;

public class HumanFactory {

	public static Human createHuman(Class c) {
		
		Human human = null; // 定义一个类型的人类
		try {
			human = (Human) Class.forName(c.getName()).newInstance();

		} catch (InstantiationException e) {
			System.out.println("必须指定人种的颜色");
		} catch (IllegalAccessException e) {
			System.out.println("人种定义错误!");
		} catch (ClassNotFoundException e) {
			System.out.println("混蛋,你指定的人种找不到!");
		}
		return human;
	}
}
test
package com.freedom.factory.abstractfactory;

import org.junit.Test;

public class TestAbstractFactory {

	@Test
	public void test() {
		System.out.println("生产的第一批人是:白人");
		Human whiteHuman = HumanFactory.createHuman(WhiteHuman.class);
		whiteHuman.say();
		whiteHuman.smile();
	}
	
	@Test
	public void test2() {
		System.out.println("生产的第二批人是:黑人");
		Human blackHuman = HumanFactory.createHuman(BlackHuman.class);
		blackHuman.say();
		blackHuman.smile();
	}
	
	@Test
	public void test3() {
		System.out.println("生产的第三批人是:黄人");
		Human yellowHuman = HumanFactory.createHuman(YellowHuman.class);
		yellowHuman.say();
		yellowHuman.smile();
	}
	

}
/*
运行结果:
生产的第一批人是:白人
white human can say anything!
white human can smile!
生产的第三批人是:黄人
yellow human can say anything!
yellow human can smile!
生产的第二批人是:黑人
black human can say anything!
black human can smile!
*/ 
当然机器总是不停地生产有时也会罢工,所以这里可以偷个懒,目前的HumanFactory只能定性生产特定人种,改造一下,让它可以批量随机生产
package com.freedom.factory.abstractfactory;

import java.util.List;
import java.util.Random;

public class HumanFactory {
	
	//批量随机生产
	public static Human createHuman(){
		Human human=null; //定义一个类型的人类
		//首先是获得有多少个实现类,多少个人种
		List<Class> concreteHumanList = ClassUtils.getAllClassByInterface(Human.class); //定义了多少人种
		//随机生产什么人种都OK
		Random random = new Random();
		int rand = random.nextInt(concreteHumanList.size());
		human = createHuman(concreteHumanList.get(rand));
		return human;
	}

	//人种定向生产
	public static Human createHuman(Class c) {
		
		Human human = null; // 定义一个类型的人类
		try {
			human = (Human) Class.forName(c.getName()).newInstance();

		} catch (InstantiationException e) {
			System.out.println("必须指定人种的颜色");
		} catch (IllegalAccessException e) {
			System.out.println("人种定义错误!");
		} catch (ClassNotFoundException e) {
			System.out.println("Sorry,你指定的人种找不到!");
		}
		return human;
	}
	
}
test
package com.freedom.factory.factory2;

import org.junit.Test;

public class TestFactory2 {

	@Test
	public void test() {
		for(int i=0; i<10; i++){
			System.out.println("---随机生产---" + i);
			Human human = HumanFactory.createHuman();
			human.say();
			human.smile();
			}
	}
	
}
/*
---随机生产---0
black human can say anything!
black human can smile!
---随机生产---1
black human can say anything!
black human can smile!
---随机生产---2
black human can say anything!
black human can smile!
---随机生产---3
white human can say anything!
white human can smile!
---随机生产---4
black human can say anything!
black human can smile!
---随机生产---5
white human can say anything!
white human can smile!
---随机生产---6
black human can say anything!
black human can smile!
---随机生产---7
black human can say anything!
black human can smile!
---随机生产---8
yellow human can say anything!
yellow human can smile!
---随机生产---9
yellow human can say anything!
yellow human can smile!
*/
 
总结一下,增加了createHuman()后,是不是这个工厂的扩展性更好了?你看你要再加一个人种,只要你继续集成Human 接口成了,然后啥都不用修改就可以生产了,具体产多少,随便你说了算,普通工厂模式就是这么简单,然后我们再引入一个问题:人是有性别的呀,有男有女,你这怎么没区别,别急,继续往下看!
工厂方法模式还有一个非常重要的应用,就是延迟始化(Lazy initialization),什么是延迟始化呢?一个对象初始化完毕后就不释放,等到再次用到得就不用再次初始化了,直接从内存过中拿到就可以了,怎么实现呢,很简单,看例子:
package com.freedom.factory.factory2;

import java.util.HashMap;

public class HumanFactory2 {
	// 定义一个MAP,初始化过的Human对象都放在这里
	private static HashMap<String, Human> humans = new HashMap<String, Human>();

	public static Human createHuman(Class c) {
		Human human = null; // 定义一个类型的人类
		try {
			//这个在类初始化很消耗资源的情况比较实用,比如你要连接硬件,或者是为了初始化一个类需要准备比较多条件(参数),通过这种方式可以很好的减少项目的复杂程度。
			// 如果MAP中有,则直接从取出,不用初始化了
			if (humans.containsKey(c.getSimpleName())) {
				human = humans.get(c.getSimpleName());
			} else {
				human = (Human) Class.forName(c.getName()).newInstance();
				// 放到MAP中
				humans.put(c.getSimpleName(), human);
			}
		} catch (InstantiationException e) {
			System.out.println("必须指定人种的颜色");
		} catch (IllegalAccessException e) {
			System.out.println("人种定义错误!");
		} catch (ClassNotFoundException e) {
			System.out.println("混蛋,你指定的人种找不到!");
		}
		return human;
	}
}
好了,这还只是工厂方法模式,我想做些拓展,比如白人有男人女人,其他人种也是,这个扩展看似很简单,只要修改各个人种的工厂类就可以了,但是这样做有什么不好呢?违反了闭包原则。那有什么方法可以避免呢?抽象方法继续看下次……


下载源码:http://download.youkuaiyun.com/detail/github_22022001/8290541

23种设计模式-工厂方法(Factory Method)设计模式 软考中级-软件设计师 工厂方法模式 阅读详情

相关推荐

Utrust4701F与Utrust2700R读写器在银河麒麟系统的安装及测试步骤说明

Utrust4701F与Utrust2700R读写器支持银河麒麟系统,广泛应用会员管理、支付管理等领域。本文将重点介绍Utrust4701F与Utrust2700R读写器在银河麒麟系统的安装及测试步骤说明。以上方法适用于主流国产操作系统,如 优麒麟(UbuntuKylin)/ 中标麒麟(NeoKylin) / UOS(统信操作系统)/ 中兴新支点 / 红旗 linux(redflag linux)/ 普华 Linux(I-soft OS) / 威科乐恩 Linux(WiOS)等

华翔天诚科技 1833

23种设计模式——工厂方法模式(Factory Method Pattern)详解

本文介绍了23种经典设计模式之——工厂方法模式(Factory Method Pattern)的说明及使用

Meteors.的博客 1381

Unity接入Google登录:Credential Manager完整集成指南与避坑实践

在移动应用开发中,第三方登录是提升用户体验和降低注册门槛的关键技术。其核心原理是通过OAuth 2.0等授权协议,安全地获取用户在平台的身份凭证。对于面向海外市场的Unity应用,Google登录因其庞大的用户基数成为首选方案。然而,随着Android系统更新和隐私政策收紧,传统的WebView登录方式面临兼容性挑战。Credential Manager作为Google推出的现代化凭据管理API,通过系统级集成解决了这一问题,它统一了密码、通行密钥和第三方登录的调用接口,显著提升了登录成功率和原生体验。在U

weixin_28025327的博客 320

java23种常用设计模式之工厂方法模式(Factory Method)

最近真是所有时间都奉献给工作了,包括下班后,连续加了两个星期的班,都没时间写博客…… (借口!!!中午两个小时够写一篇啦!!!哈哈,我错了,是懒……) 23个设计模式才写了3个,我只想说一声,“”革命尚未成功,同志仍需努力呀!" 好了,胡扯到此结束,回到正题。今天我们来捋一捋工厂方法模式。这个模式很容易理解,如其名,无非就是为了偷懒,对某种事物进行工厂式的批量生产。 工厂方法有三种模式:普

The code world of freedom 580

matlab生成blocks、bumps和doppler标准测试信号

关键函数:wnoise使用方式X = wnoise(FUN,N) [X,XN] = wnoise(FUN,N,SQRT_SNR) [X,XN] = wnoise(FUN,N,SQRT_SNR,INIT)X = wnoise(FUN,N) 返回由 FUN给出的信号,长度为2^N,幅值范围[0,1].[X,XN] = wnoise(FUN,N,SQRT_SNR) ,返回了一个测试信号X,以及一个加噪

ZSZ_shsf的博客 6580

华为海思IC前端中后端(COT&XPU)岗位笔试机考题

华为海思COT和XPU部门IC前端,IC中端,IC后端岗位笔试真题分享

weixin_37584728的博客 3362

Factory Method工厂方法模式(Java代码实现)——创建型模式

对于MessageDigest.getInstance()方法也是如此,比如我们可以通过`MessageDigest.getInstance("MD5");`来获取MD5算法。 并且在Effective Java一书中,第二章第一条就是`用静态工厂方法代替构造器`。

MrYushiwen的博客 1971

BERT之提取特征向量 及 bert-as-server的使用

本文内容列表提取句向量1、句向量简介1-1传统句向量1-2、BERT句向量2、 extract_features.py源码分析2-1 main函数 前一篇文章 BERT介绍及中文文本相似度任务实践 简单介绍了使用BERT进行中文文本相似度计算的方法,这篇文章着重对特征提取方法进行讲述。 提取句向量 1、句向量简介 1-1传统句向量 更多采用word embedding的方式取加权平均,该方法的一大...

ling620的专栏 1万+

Java23种设计模式的研究之一(工厂方法模式(Factory Method))

Java开发工作久了,难免对一些Java中的技术想要探究一番。现在就Java经典的23种设计模式倒腾一番。          1、工厂方法模式: 在我们平时应用中其实工厂方法模式分为3种模式、             1-1:普通工厂模式,就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。首先看下关系图:                    代码:(借鉴一个邮件发送类和短信发

MsFzzy的博客 425

SMART200如何实现多次调用子程序带定时器功能

1、西门子200PLC的子程序由于很多限制条件,如果希望建立一个可以多次调用的子程序,那么这个子程序里是不能含有定时器指令的,所以我们只能退而求其次了。建议将沿指令(上升沿、下降沿)放在多次调用子程序的外面。 2、可以提供不同的时基,提供不同时间的定时 3、实现秒定时 5、子程序内部: STL代码: 1、时基信号由外部提供、 可以提供不同的时基信号 2、实现循环定时开关 LD #Start:L0....

RXXW_Dor的博客 1万+

Google Earth Engine(GEE)——全球影像数据正确下载方式和注意事项

今天看到有人担心全球影像能不能下载的问题? 有时候我们会用到全球的数据,但是如何下载全球的数据呢? 首先如果没有全球的矢量边界我们会不会无法下载全球的数据,答案当然是可以的,因为我们在边界筛选的过程中filterBounds(),就是为了筛选边界,当我们不进行边界筛选的时候,自然而然默认的边界范围就是全球的,但是紧接着会面临其他两个问题:1如何下载?2如何在不缩小分辨率的情况下下载成功? 对于第一个问题我们如何下载?还是按照正常的逻辑利用export直接倒出到Google硬盘当中, 代码:

此星光明博客 3771

设计模式之工厂方法模式(Factory Method)

本文介绍Java中23个设计模式中的工厂方法模式。一、概念 工厂方法模式(Factory Method)是一种常用的对象创建型设计模式,此模式的核心精神是封装类中不变的部分,提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。它的核心结构有四个角色,分别是抽象工厂,具体工厂,抽象产品,具体产品。二 、作用 工厂方法经常用在以下两种情况中: 第一种情况是对于某个产

蜗牛要飞的博客 414

微信公众平台 - 微信内置浏览器 WeixinJSBridge.invoke(‘xxx‘) API 报错:system:access_denied(常见于微信支付、分享朋友圈/转发好友等功能)解决方案

微信支付提示System:access_denied,调用微信支付返回:system:access_denied为什么,安卓版微信支付偶尔出现system:access_denied,微信公众号开发分享出现system:access_denied,system:access_denied如何解决?微信WeixinJSBridge.invoke(‘xxx‘)API调用后出现报错,微信内部H5WeixinJSBridge.invokesystem:access_denied,使用微信jssdk时报ac

🏆 前端领域优质创作者 5145

Java 之 23 种设计模式解析——1.工厂方法模式(Factory Method)

1、工厂方法模式(Factory Method) 简单工厂模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,必须对工厂类进行修改,这违背了闭包原则,所以,从设计角度考虑,有一定的问题,如何解决?就用到工厂方法模式, 创建一个工厂接口和创建多个工厂实现类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了, 不需要修改之前的代码。 请看例子: [java] vi...

毕富国的博客 698

深度学习工具包 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")

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

Java GoF 23种设计模式-创建型模式-工厂方法模式(Factory Method Pattern)

文章目录一、模式定义二、模式动机三、模式结构四、代码实现五、缺点 一、模式定义 工厂方法模式(Factory Method Pattern)又称为工厂模式,也叫虚拟构造器(Virtual Constructor)模式或者多态工厂(Polymorphic Factory)模式,它属于创建型模式。 在工厂方法模式中,工厂父类负责定义创建产品对象的公共接口,而工厂子类则负责生成具体的产品对象,这样做的目的是将产品类的实例化操作延迟到工厂子类中完成,即通过工厂子类来确定究竟应该实例化哪一个具体产品类。 工厂方法模式

WU4566285的博客 432

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

java factory method_java设计模式:工厂方法模式(Factory Method)

工厂方法模式阅读目录:简单工厂模式介绍UML类图参考代码总结工厂方法模式介绍UML类图参考代码总结前言:《大话设计模式》里有一小节叫'活字印刷,面向对象'的,讲了一个小故事,大意如下:话说三国时期,曹操带领大军驻扎于赤壁。军船相连,气势恢宏,眼看要灭掉东吴,统一天下,曹操甚悦,于是大宴群臣。席间曹操诗兴大发,不觉吟道:"喝酒唱歌,人生真爽。……"。众文武齐呼:"丞相好诗!"。于是一臣子速命印刷工匠...

weixin_39722692的博客 173

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

23种常用设计模式之工厂模式:工厂方法模式

说明 工厂方法模式(FACTORY METHOD)是一种常用的类创建型设计模式,此模式的核心是封装类中变化的部分,提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。它的核心结构有四个角色,分别是抽象工厂;具体工厂;抽象产品;具体产品 应用场景 对于某个产品,调用者清楚地知道应该使用哪个具体工厂服务,实例化该具体工厂,生产出具体的产品来。Java Collec...

学而时习之 267

Java开发之设计模式--工厂方法模式(Factory Method)

设计模式第2篇--工厂方法模式(Factory Method)

ZaneLove's blog 1003

Java的23中设计模式之工厂方法模式(二)

一、什么是工厂方法模式 工厂方法模式(FACTORY METHOD)是一种常用的类创建型设计模式,此模式的核心精神是封装类中变化的部分,提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。它的核心结构有四个角色,分别是抽象工厂、具体工厂、抽象产品、具体产品。 二、工厂方法模式特点 简单工厂模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,...

Aboutdream的博客 329

工厂方法模式(Factory Method)

工厂模式是一种创建型设计模式,通过将对象创建和使用分离来提升代码扩展性。文章从支付系统案例出发,分析了直接实例化对象的问题(违反开闭原则、代码臃肿),并展示了三种工厂模式的实现方式:简单工厂(单一工厂类)、工厂方法(抽象工厂接口)和抽象工厂(创建产品族)。文章比较了各模式的优缺点,指出工厂方法符合开闭原则但会增加类数量,而抽象工厂适合创建相关对象但扩展困难。最后还介绍了Spring框架中工厂模式的应用(BeanFactory)及其与依赖注入的关系,建议现代开发优先使用DI但需理解工厂模式原理。

m0_56853686的博客 696

java设计模式:工厂方法模式(Factory Method)

工厂方法模式 返回设计模式目录 阅读目录: 简单工厂模式 介绍 UML类图 参考代码 总结 工厂方法模式 介绍 UML类图 参考代码 总结 前言:   《大话设计模式》里有一小节叫'活字印刷,面向对象'的,讲了一个小故事,大意如下:   话说三国时期,曹操带领大军驻扎于赤壁。军船相连,气势恢宏,眼看要灭掉东吴,统一天下,曹操甚...

259

设计模式:创建型模式--工厂方法模式(Factory Method Pattern)

设计模式:创建型模式–工厂模式(Factory Pattern) 文章目录设计模式:创建型模式--工厂模式(Factory Pattern)1. 引入2. 简单工厂模式2.1 组成结构2.2 实现细节2.3 优缺点2.4 扩展实现3. 工厂模式3.1 概念3.2 组成结构3.3 实现细节3.4 优缺点 本文章中将介绍两种工厂模式: 简单工厂模式(Simple Factory Pattern)(不属于GOF的23种经典设计模式)。 工厂方法模式(Factory Pattern)。 工厂模式(Factor

ZZay's 510

Java23种设计模式 工厂方法模式【Factory Method Pattern】

本文章转载大佬CBF4LIFE的文章 博客地址:https://www.cnblogs.com/cbf4life/ 女娲补天的故事大家都听说过吧,今天不说这个,说女娲创造人的故事,可不是“造人”的工作,这 个词被现代人滥用了。这个故事是说,女娲在补了天后,下到凡间一看,哇塞,风景太优美了,天空是湛 蓝的,水是清澈的,空气是清新的,太美丽了,然后就待时间长了就有点寂寞了,没有动物,这些看的到 都是...

宇智波带土 190

创建型模式:工厂方法模式(Factory Method Pattern)

经过很多大神的总结,目前Java中一共23种经典的设计模式! 按照目的,设计模式可以分为以下三种用途: 1.创建型模式:用来处理对象的创建过程 2.结构型模式:用来处理类或者对象的组合 3.行为型模式:用来对类或对象怎样交互和怎样分配职责进行描述 创建型模式用来处理对象的创建过程,主要包含以下5种设计模式:  工厂方法模式(Factory Method Patte

未来,你好! 509
上一篇: java23种常用设计模式之抽象工厂模式(Abstract Factory)
下一篇: java23种常用设计模式之抽象工厂模式(Abstract Factory)2
freedom1993
博客等级 码龄12年 25粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值