23种设计模式

http://blog.youkuaiyun.com/zhangerqing/article/details/8194653

创建对象:

1,单例(Singleton)

作用:系统中只有一个该类的实例。

public class LazySingleton {
	private static LazySingleton singleton = null;// 不再做实例化操作
	private LazySingleton(){};// 构造方法声明为私有,这样就保证了只能有一个对象存在
	// 提供一个外部得到类的方法
	public synchronized static LazySingleton getInstance() {
		if (null == singleton) {
			synchronized (LazySingleton.class) {
				if (null == singleton) {
					singleton = new LazySingleton();
				}
			}
		}
		return singleton;
	}
}


2,工厂

作用:将实例化交给一个工厂类来管理。如果你现在想增加一个功能:发及时信息,则只需做一个实现类,实现Sender接口,同时做一个工厂类,实现Provider接口,就OK了,无需去改动现成的代码。这样做,拓展性较好

 

public interface Sender {
	public void Send();
}
public class MailSender implements Sender {
	@Override
	public void Send() {
		System.out.println("this is mailsender!");
	}
}
public class SmsSender implements Sender {

	@Override
	public void Send() {
		System.out.println("this is sms sender!");
	}
}

 

public interface Provider {
	public Sender produce();
}
public class SendMailFactory implements Provider {
	@Override
	public Sender produce(){
		return new MailSender();
	}
}
public class SendSmsFactory implements Provider{
	@Override
	public Sender produce() {
		return new SmsSender();
	}
}
public class Test {
	public static void main(String[] args) {
		Provider provider = new SendMailFactory();
		Sender sender = provider.produce();
		sender.Send();
	}
}


3,构造者

作用:将实例化交给一个建造者来管理。

 

public class User{
	private String name;
	private int age;
	private boolean sex;
	public static class Builder {
		private String name;
		private int age;
		private boolean sex;
		public Builder name(String val) {
			name = val;
			return this;
		}
		
		public Builder age(int val) {
			age = val;
			return this;
		}
		
		public Builder sex(boolean val) {
			sex = val;
			return this;
		}
		
		public User build() {
			return new User(this);
		}
	}
	
	private User(Builder builder)  {
		name = builder.name;
		age = builder.age;
		sex = builder.sex;
	}
}
User user = new User.Builder.name("hello").age(18).sex(true).build();

 

4,原型(Prototype)

作用,将实例化通过clone()方法,即内存拷贝的方式,以此减少创建相似对象的消耗。

 

public class User {
	private String name;
	/* 浅复制 */
	public Object clone() throws CloneNotSupportedException {
		User user = (User) super.clone();
		return user;
	}
	/* 深复制 */
	public Object deepClone() throws IOException, ClassNotFoundException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(this);
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		return ois.readObject();
	}<span style="font-family: Arial, Helvetica, sans-serif;">}</span>


程序结构:

1,适配器

作用:

c++23种设计模式 设计模式 设计模式(Design Pattern)代表了最佳的实践,在面向对象的编程中被很多老鸟们反复使用。使用设计模式有很多好处: 可重用代码 保证代码可靠性 使代码更易被他人理解 设计模式六大原则 a. 单一职责原则:就一个类来说,应该只有一个引起它变化的原因 一个类做一件事情,避免职责过多。比如这种情况是不太好的,在一个 Activity中既有 bean 文件,又有 http 请求,... 阅读详情

相关推荐

设计模式GOF23简介

公元1991年,软件界有四位大侠,总结了前人的一些设计模式,并进行分门别类,一共得出23种设计模式供软件开发者进行参考复用,在经过几代人的开发实践后,设计模式在各个项目中大放光彩,这四位大侠是Gamma, Helm, Johnson & Vlissides,Addison-Wesley, 全地球程序员为了表示对设计模式的敬仰与崇拜,因此设计模式又称为GOF23。 设计模式主要有三大类,23小类,就像少林七十二绝技,各种招式技法都有,但是在项目中却不那么好用,需要有敏...

琅嬛福地 788

彻底搞懂设计模式DesignPattern-23种设计模式整理

设计模式介绍 设计模式是程序员在面对同类软件工程设计问题所总结出来的有用的经验,模式不是代码,而是某类问题的通用解决方案, 设计模式(Design pattern)代表了最佳的实践。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。 设计模式的本质提高 软件的维护性,通用性和扩展性,并降低软件的复杂 度。 <<设计模式>> 是经典的书,作者是 Erich Gamma、 Richard Helm、 Ralph Johnson 和 John Vlissides

Ping 1106

2080Ti双卡开启NVLink

本文介绍了如何在Ubuntu 22.04系统下给2080Ti双卡开启NVLink的方法。

flymyd的博客 2899

23种设计模式概述

23种设计模式 概念 结构图

qq_25091281的专栏 2万+

innovus实战攻略 | 用setUsefulSkewMode解锁时序优化的“隐藏技能”!

就像时序优化的“瑞士军刀”,参数虽多,但掌握了分类逻辑后,用起来其实很简单!如果你有更绝的用法,欢迎在评论区分享,大家一起卷起来!简单来说,它就是时序优化的“乾坤大挪移”。通过调整触发器的时钟到达时间,把关键路径的建立时间“借”给非关键路径,从而实现全局时序收敛。别急,这个命令就是你的“时序救星”!(工具最多只能借1.2ns的裕量,防止“借过头”导致新问题!这个参数能帮你兜底!(对关键路径“下死手”,确保优化到位!(设置上限,给工具套上“紧箍咒”!(直接跳过边界,避免优化反噬!(全局管理,防止“借过头”!

weixin_50820814的博客 1354

【100%通过率】华为od统一考试B卷【需要打开多少监视器】JAVA&Go 实现

某长方形停车场,每个车位上方都有对应监控器,当且仅当在当前车位或者前后左右四个方向任意一个车位范围停车时,监控器才需要打开:给出某一时刻停车场的停车分布,请统计最少需要打开多少个监控器

MISAYAONE的博客 1万+

设计模式的理解:对23个设计模式的总结

设计模式名 ,链接可用 设计模式 意图 适用的场景 关键实现过程 优点 缺点 备注 1 模板模式 通常定义出一个稳定的骨架,特定的内容的实现延迟至子类中去实现 易变,容易根据实际需求改动的代码块,对此代码块进行延迟到子类中实现 不变的算法在基类中保留,易变的算法变成虚函数由子类实现 把不确定部分剥离开来,实现确定的部分。让将来的调用者简单实现不确定的方法就可以达到想要的效果 对调用者屏蔽了稳定的代码,使调用者虽了解使用..

superSmart_Dong的博客 380

VCS NLP 低功耗验证系列(六):功耗分析与优化——SAIF 报告与验证效率提升

本文是VCS NLP低功耗验证系列的第六篇,主要解决功耗数据采集和验证效率优化问题。文章首先介绍了SAIF(Switching Activity Interchange Format)文件在功耗分析中的作用,详细讲解了VCS的Region-Based SAIF功能,包括三个关键系统任务($saif_region_create、$saif_region_exclude、$saif_region_monitor)的使用方法和工程实践建议。接着从编译侧、运行侧和方法学侧三个维度提出了NLP验证效率优化策略,特别强

元直的博客 470

java23种设计模式一(连载)

设计模式概要 设计模式,顾名思义,它是一种模式,在面向对象中,它运用类与它们的方法来达到目标。使用它便于代码的可重用和可读性,有利于系统的维护。《Design pattern》一书中首次提出了23种设计模式,倘若你想成为编程高手,就必须要学习设计模式。 以下...

chongsi9495的博客 134

在 SAP Gateway 主机上把 SAML 2.0 配置为 Service Provider:从架构到落地的完整实战

本文详细介绍了在SAP Gateway主机上配置SAML 2.0作为Service Provider的全流程。从概念梳理到实际操作,涵盖了关键步骤:启用本地SP服务、通过反向代理导出元数据、在IdP侧完成对接、配置信任关系与Artifact绑定、设置NameID身份联合等核心环节。特别强调了HTTP Artifact绑定的背道通信机制和证书配置要点,并针对常见错误提供了排障指引。文章注重实操性,结合SAP官方文档与社区最佳实践,为运维团队提供了一套完整的SAML SSO实施框架。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 149

ANSYS——模态分析的理论基础

ANSYS模态分析理论基础

python_AI_fans的博客 9072

23种设计模式彩图

《The Zen of Design Patterns》 —《设计模式之禅》 书中的23种设计模式彩图:

915

【雕爷学编程】Arduino智能家居之DS18B20温度传感器

1、温度和湿度控制:通过连接温度传感器和湿度传感器,Arduino可以实时监测室内环境的温度和湿度,并通过控制空调、加热器或加湿器等执行器,实现室内温湿度的自动调节。设计用户友好的界面和操作方式,提供简单直观的控制和反馈机制,以及考虑用户习惯和需求,能够提升系统的整体用户体验。这意味着用户可以根据自己的需求和创意,自定义和定制智能家居系统的功能和外观。5、能源管理:Arduino可以与电能监测模块和智能插座等设备结合使用,实时监测家庭能源的使用情况,并通过自动控制电器设备的开关,实现能源的有效管理和节约。

雕爷学编程 2873

设计模式汇总一、java 23种设计模式汇总

23-design-pattern 计模式分为三大类 1、创建型模式,共五种: 1-1:单例模式—— [com.sjms.danli] 1-2:工厂方法模式 —— [com.sjms.factory] 1-3:抽象工厂模式 —— [com.sjms.abstractfactory] 1-4:建造者模式 —— [com.sjms.builder1]、[com.sjms.buil...

AI技术改变世界 433

OpenClaw零基础教程:30分钟搭建你的第一个AI自动化助手

别再看那些满是代码、专业术语的教程了,那些都是给程序员看的。这篇教程,我把所有步骤拆到了极致,你跟着点鼠标就行,点错了都没关系,大不了重装一遍,5分钟的事。

2601_94871597的博客 96

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

js实现23种设计模式

js实现23种设计模式 最近在学习面向对象的23种设计模式,使用java 和 javascript 实现了一遍,但是因为目前大三,还没有比较正规的大项目经验,所以学习的过程种我觉得如果没有一定的项目经验的话很难去完全掌控,所以学习的过程中只是大致学习了每种设计模式的特点,我觉得在学习的过程中应该自己找场景实现,这样学习效果很好,下面是代码,当然仅供参考。下面是代码: 创建型模式 单例模式 三要素:...

weixin_33749131的博客 2840

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

图文详解23种设计模式关系

设计模式:可复用面向对象软件的基础》是软件工程领域的经典著作,由四位顶尖专家(Erich Gamma、Richard Helm、Ralph Johnson和John Vlissides,合称GoF)编写,首次系统化提出了23种设计模式,分为创建型、结构型和行为型三大类‌。该书被誉为面向对象设计的"圣经",其核心价值在于总结可复用的解决方案,帮助开发人员更好地组织代码,提升代码的可维护性、扩展性和团队协作效率。‌‌

独码乐,不如众码乐,乐享其中 524

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

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Android 23种设计模式

转自:Android 23种设计模式 - 简书 Android 23种设计模式 1、Android 单例模式 2、Android Builder模式 3、Android 原形模式(深浅拷贝) 4、Android 工厂模式 5、Android 策略模式 6、Android 状态模式 7、Android 责任链模式 8、Android 命令模式 9、Android 观察者模式 10、Android 备忘录模式 11、Android 迭代器模式 12、Android 模板方法模式 13、Android 访问者

Gabriel的专栏 4485

探讨23种设计模式之外的现代设计模式

虽然GoF 23种设计模式为我们提供了坚实的基础,但随着软件工程领域的不断发展,我们也应该保持开放的心态,学习和应用新的设计模式。每一种模式都有其适用的场景和局限性,了解它们可以帮助我们在正确的时间做出最佳的选择,从而构建出更加健壮和高效的软件系统。PHP官网。

软件架构师笔记 1130

GOF23种设计模式(Design Pattern)总结

GOF23种设计模式(Design Pattern)总结 比较   设计模式 常用程度 适用层次 引入时机 结构复杂度 Abstract Factory 比较常用 应用级 设计时 比较复杂 Builder 一般 代码级 编码

lionzl的专栏 682

23设计模式彩图

23设计模式彩图

Cactus 748
上一篇: JUnit4
下一篇: 23种设计模式
hellobbboy
博客等级 码龄17年 20粉丝 52原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值