Java设计模式之从[欢迎界面]分析模板方法(Template Method)模式

Android 设计模式入门到精通之十五:模板方法模式(Template Method) 设计模式项目源码请移步:https://github.com/caobaokang419/WeatherApp(欢迎Github Fork&Star,代码设计模式&框架设计实现不妥之处,请帮忙指正),谢谢! 模板方法模式(TemplateMethod) 1. 概念&应用场景 Define the skeleton of an algorithm in an o... 阅读详情

  模板方法是在抽象类中最常用的模式了(应该没有之一),它定义一个操作中算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义算法的某些步骤。

  例如我们要编写一个欢迎界面,如果用户是第一次打开本软件,则弹出一个欢迎的提示。为了能够实现复用,将这个机制当成一个基类,Java代码如下:

abstract class FirstLogin{
    abstract protected void showIntro();
    boolean firstLogin;
    public FirstLogin(boolean firstLogin){
        this.firstLogin = firstLogin;
    }
    public void show(){
        if (firstLogin){
            showIntro();
        }
    }
}

class HelloWorld extends FirstLogin{
    public HelloWorld(boolean firstLogin) {
        super(firstLogin);
    }
    protected void showIntro(){
        System.out.println("欢迎你第一次使用本程序! Hello world!");
    }
}
public class TemplateMethod
{
    public static void main(String[] args) {
        HelloWorld helloWorld1 = new HelloWorld(false);
        System.out.println("HelloWorld 1:");
        helloWorld1.show();
        HelloWorld helloWorld2 = new HelloWorld(true);
        System.out.println("HelloWorld 2:");
        helloWorld2.show();
    }
}

  FirstLogin中的show方法为模板方法。它用了showIntro这个抽象方法定义了出现欢迎界面的算法,而它的子类将来实现showIntro方法。也就是说,基类用于实现不变的部分,而将可变的部分留给子类,是十分常见的一种模式。

【愚公系列】二十三种设计模式(二十二)-模板方法模式(Template Method Pattern) 设计模式(Design Pattern)是软件开发领域的宝贵经验,是多人反复借鉴和广泛应用的代码设计指导。它们是一系列经过分类和归纳的代码组织方法,旨在实现可重用性、可维护性和可理解性。使用设计模式,我们能够编写高质量的代码,使其更易于他人理解,并提供了代码可靠性的保证。毫无疑问,设计模式对个人、团队和整个系统都带来了显著的益处。它们将代码开发提升到工程化水平,为软件工程构建提供了坚实的基础,就如同大厦的一块块精巧的砖石一样。在项目中明智地应用设计模式可以完美地解决各种复杂问题。 阅读详情

相关推荐

vue-first-login

首次登录 项目设置 npm install 编译和热重装以进行开发 npm run serve 编译并最小化生产 npm run build 整理和修复文件 npm run lint 自定义配置 请参阅。

First Login

First Login

weixin_41467451的博客 1635

ROC-RK3588S-PC 刷机 安装Android系统

rk3588刷机,装系统

Wjz_www的博客 4835

java swing 欢迎界面_用java做一个欢迎界面

使用javafx的Media,MediaPlayer,MediaView。代码如下:import java.io.File;import javafx.application.Application;import javafx.beans.binding.Bindings;import javafx.beans.property.ReadOnlyProperty;import javafx.bea...

weixin_35775608的博客 1068

探索Vortex开源GPGPU:RISC-V SIMT架构(4-1),Execute SFU(1)

本文详细分析了Vortex RISC-V内核6级流水线中Execute阶段的SFU(特殊功能单元)模块。重点介绍了SFU的数据流结构,包含dispatch_unit、pe_switch、csr_unit、wctl_unit和gather_unit五个子模块。文章深入解析了warp控制指令wspawn和tmc的实现机制:wspawn用于激活指定数量的warp并设置新PC值,tmc则用于控制线程掩码和warp状态。通过C代码和汇编指令的对照分析,阐明了这些指令在并行计算中的关键作用,包括线程激活、状态切换和执行

weixin_55313207的博客 1363

QT实现串口通信

要实现串口通信,需要知道串口通信需要的信息 主要参数有:波特率、校验位、数据位、停止位、控制流 主要操作有:串口的打开和关闭、刷新设备串口、接发数据、开关显示灯等。 实现效果如图: 最后附赠完整源码。 第一步:在头文件中引入 QtSerialPort 类的两个头文件(必须引入) // 引入串口通信的两个头文件(第一步) #include <QtSerialPort/QSerialPort> // 提供访问串口的功能 #include <QtSerialPo

m0_49456900的博客 6万+

用Java Swing 写欢迎界面

import java.awt.*;import java.awt.event.*;import javax.swing.*;class WelcomeWindow extends JWindow{//welcome window. public WelcomeWindow(String filename,Frame f,int waitTime){  super(f);  JLabel l =

chenheping的专栏 1964

Ansys Electronics Desktop仿真——HFSS线圈寄生电阻,电感

Ansys Electronics Desktop仿真——HFSS线圈寄生电阻,电感

冲击10w 1万+

java欢迎页面说明_web页 Java Web- [页面功能]详细说明

分页简介分页功能是网页中非常常见的功能,其功能是将数据分为多个页面以供显示。当我们不使用分页功能时,我们将面临许多问题:分页类别分页的实现分为两种类型,即真正分页和错误分页,即物理分页和逻辑分页。1.真实分页(物理分页):2.假分页(逻辑分页):传统分页方法错误分页的实现非常简单。您只需要准备一个集合来保存从数据库中检索到的所有数据,然后根据当前页面的代码号,取出相应的数据范围并显示出来。这里我们...

weixin_35261385的博客 521

【Unity】入门教程第一期-下载安装Unity编辑器(下)

讲解如何在Unity Hub中下载Unity编辑器以及IED环境

Xiaoxin的博客 2041

Win11网络卡顿?用Wireshark抓包5分钟定位问题(保姆级实战)

本文详细介绍了如何使用Wireshark在Win11系统中快速定位网络卡顿问题。通过5分钟抓包分析,作者成功发现TCP重传率高达37%的罪魁祸首,并提供了从准备工作到实战分析的保姆级教程,帮助用户解决游戏卡顿、视频会议延迟等常见网络问题。

weixin_28839629的博客 306

欢迎界面的java程序,Java设计模式之从[欢迎界面]分析模板方法(Template Method)模式...

模板方法是在抽象类中最常用的模式了(应该没有之一),它定义一个操作中算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义算法的某些步骤。例如我们要编写一个欢迎界面,如果用户是第一次打开本软件,则弹出一个欢迎的提示。为了能够实现复用,将这个机制当成一个基类,Java代码如下:abstract class FirstLogin{abstract protected voi...

weixin_33037313的博客 430

[Python + UG NX 二次开发新手教程] 第五课 采用Python / UF 开发模式

在 NX 二次开发里看到的“UF”是的缩写,它是 Siemens 提供的集合,也是整个 NX Open 体系里最贴近内核、历史最悠久的一套接口。相当于 NX 的“系统调用”——只要 NX 能做的事,UF 几乎都能调得动。Siemens 从 NX 12 开始把原来的 C 接口(UF)全部打包进了官方 Python 模块,命名空间为 NXOpen.UF.*,所以只要 NX 安装目录里带了 NXOpen\UF 子模块,就能在 Python 里直接调用 UF 函数。

温良 1004

【设计模式】springboot3项目整合模板方法深入理解设计模式之模板方法(Template Method)

模板方法模式是一种行为型设计模式,用于定义一个算法的骨架,将具体的实现延迟到子类中。模板方法模式允许我们定义一个抽象类,其中包含一个模板方法和一些抽象方法,供具体子类实现。这样,通用的操作被封装在模板方法中,而具体的实现细节则由子类来完成。

终于等到你啦~欢迎来到我的知识空间 这里是苏泽的成神之路 2663

YOLO11涨点优化:知识蒸馏 | 引入FGD(Focal and Global Distillation)蒸馏,让轻量学生模型汲取大模型全局感知力

文章摘要 目标检测模型YOLO11在轻量化部署中存在"全局盲区"问题,即轻量模型感受野不足导致大尺度场景下性能下降。知识蒸馏技术FGD(Focal and Global Distillation)通过双分支机制有效解决这一问题:Focal Distillation分离前景背景特征,让学生模型聚焦关键区域;Global Distillation传递像素间关系信息,弥补全局感知缺陷。实验表明,FGD可使YOLO11轻量版mAP提升2.5%以上,且不增加推理耗时。本文详细解析了FGD原理,并给出YOLO11上的实

2601_95807009的博客 226

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

【设计模式】【行为型模式】模板方法模式(Template Method)

模板模式(Template Method Pattern)是一种行为设计模式,它定义了一个算法的框架,并允许子类在不改变算法结构的情况下重新定义算法的某些步骤。模板模式通过将算法的通用部分放在父类中,而将可变部分留给子类来实现。● 抽象类(Abstract Class):定义一个算法的框架,包含一个模板方法和一些基本操作(可以是抽象的或已经实现的)。

flzjkl的博客 1177

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

23种设计模式——模板方法模式(Template Method Pattern)详解

本文介绍23种经典设计模式之——模板方法模式(Template Method Pattern)的介绍及使用

Meteors.的博客 826

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

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Java设计模式 Design Pattern:模板方法 Template Method

<br /><br />意图Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. 在一个操作中定义一个算法的骨架,在子类中改变某些步骤Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. 模板方法使得子类可以重新

OYJJ的专栏 1643

设计模式之模板方法模式(Template Method)

面试题文档来啦,内容很多,485页!由于笔记的内容太多,没办法全部展示出来,下面只截取部分内容展示。

F1520080的博客 718

设计模式之模板方法模式Template Method Pattern-Java版

一、定义 The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. 模板方法模式定义了一种算法的框架,将部分步骤

qianmojl的博客 164

JAVA:模板方法模式(Template Method Pattern)的技术指南

摘要:模板方法模式是一种行为型设计模式,通过定义算法框架和可变步骤,允许子类在不改变结构的情况下重写部分实现。核心包含抽象类(定义模板方法)、具体类(实现具体步骤)和固定的算法流程。以饮料制作为例,展示了如何复用煮水、倒入杯中等固定步骤,同时允许子类自定义冲泡和添加调料方法。该模式优点是可复用代码、保持一致性,缺点是可能增加子类数量。适用于固定流程、相似逻辑系统或框架设计等场景。

木头 545

java template method_Java之模板方法模式(Template Method)

1. 概念:定义一个算法的骨架,而将一些实现步骤延迟到子类中。把不变的行为搬到超类,去除子类中重复的代码来体现他的优势。2. UML图:3.代码:public abstract class Templete{private void beforeOperation(){System.out.println("This acton before the operation!");}private v...

weixin_36472567的博客 187

【设计模式】C++/C#/Java实现Template Method模式

本文属于「设计模式」系列文章之一。这一系列开始时间为2021/10/27,着重于「设计模式的学习与实践」。由于文章内容随时可能发生更新变动,欢迎关注和收藏设计模式系列文章汇总目录一文以作备忘。需要特别说明的是,为了透彻理解和全面掌握设计模式,本系列文章中参考了诸多博客、教程、文档、书籍等资料,限于时间精力有限,这里无法一一列出。部分重要资料的不完全参考目录如下所示,在后续学习整理中还会逐渐补充: 大话设计模式(C# Design Patterns),程杰著,清华大学出版社, (国外经典书籍)设计模式:可.

memcpy0的博客 257

设计模式 - 行为型设计模式 - 模板方法模式(Java)

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net Definition Define the skeleton of an algorithm in an operation, deferring some stepsto subclasses. Template Method lets su...

了解➔熟悉➔掌握➔精通 5万+
上一篇: Java设计模式之从[游戏中的兵种状态转换]分析状态(State)模式
下一篇: 一、从Java、C#到C++ (为什么C++比较难)
Froser
博客等级 码龄17年 131粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值