Java的常用的几种设计模式

Java开发常用的几种设计模式——让代码更“顺溜”的秘籍 Java设计模式实战指南:6大常用模式让代码更高效 本文介绍了Java开发中6种实用设计模式的应用场景和实现方式: 单例模式 - 确保全局唯一实例,适用于配置管理、连接池等场景,通过双重检查锁实现线程安全。 工厂模式 - 封装对象创建逻辑,降低耦合度,适合支付系统等需要创建多种相似对象的场景。 策略模式 - 运行时选择不同算法,使电商促销等业务逻辑更灵活。 代理模式 - 控制对象访问,实现权限校验和日志记录等功能。 观察者模式 - 建立一对多通知机制,适用于微博关注等事件通知场景。 装饰器模式 - 动态扩展 阅读详情

java的设计模式大体上分为三大类:

  • 创建型模式(5种):工厂方法模式,抽象工厂模式,单例模式,建造者模式,原型模式。
  • 结构型模式(7种):适配器模式,装饰器模式,代理模式,外观模式,桥接模式,组合模式,享元模式。
  • 行为型模式(11种):策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

设计模式遵循的原则有6个:

1、开闭原则(Open Close Principle)

  对扩展开放,对修改关闭。

2、里氏代换原则(Liskov Substitution Principle)

  只有当衍生类可以替换掉基类,软件单位的功能不受到影响时,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为。

3、依赖倒转原则(Dependence Inversion Principle)

  这个是开闭原则的基础,对接口编程,依赖于抽象而不依赖于具体。

4、接口隔离原则(Interface Segregation Principle)

  使用多个隔离的借口来降低耦合度。

5、迪米特法则(最少知道原则)(Demeter Principle)

  一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。

6、合成复用原则(Composite Reuse Principle)

  原则是尽量使用合成/聚合的方式,而不是使用继承。继承实际上破坏了类的封装性,超类的方法可能会被子类修改。

1. 工厂模式(Factory Method)

  常用的工厂模式是静态工厂,利用static方法,作为一种类似于常见的工具类Utils等辅助效果,一般情况下工厂类不需要实例化。

interface food{}

class A implements food{}
class B implements food{}
class C implements food{}
public class StaticFactory {
    private StaticFactory(){}
    
    public static food getA(){  return new A(); }
    public static food getB(){  return new B(); }
    public static food getC(){  return new C(); }
}

class Client{
    //客户端代码只需要将相应的参数传入即可得到对象
    //用户不需要了解工厂类内部的逻辑。
    public void get(String name){
        food x = null ;
        if ( name.equals("A")) {
            x = StaticFactory.getA();
        }else if ( name.equals("B")){
            x = StaticFactory.getB();
        }else {
            x = StaticFactory.getC();
        }
    }
}

2. 抽象工厂模式(Abstract Factory)

  一个基础接口定义了功能,每个实现接口的子类就是产品,然后定义一个工厂接口,实现了工厂接口的就是工厂,这时候,接口编程的优点就出现了,我们可以新增产品类(只需要实现产品接口),只需要同时新增一个工厂类,客户端就可以轻松调用新产品的代码。

  抽象工厂的灵活性就体现在这里,无需改动原有的代码,毕竟对于客户端来说,静态工厂模式在不改动StaticFactory类的代码时无法新增产品,如果采用了抽象工厂模式,就可以轻松的新增拓展类。

interface food{}

class A implements food{}
class B implements food{}

interface produce{ food get();}

class FactoryForA implements produce{
    @Override
    public food get() {
        return new A();
    }
}
class FactoryForB implements produce{
    @Override
    public food get() {
        return new B();
    }
}
public class AbstractFactory {
    public void ClientCode(String name){
        food x= new FactoryForA().get();
        x = new FactoryForB().get();
    }
}

3. 单例模式(Singleton)

   在内部创建一个实例,构造器全部设置为private,所有方法均在该实例上改动,在创建上要注意类的实例化只能执行一次,可以采用许多种方法来实现,如Synchronized关键字,或者利用内部类等机制来实现。

public class Singleton {
    private Singleton(){}

    private static class SingletonBuild{
        private static Singleton value = new Singleton();
    }

    public Singleton getInstance(){  return  SingletonBuild.value ;}
    
}

4.建造者模式(Builder)

  在了解之前,先假设有一个问题,我们需要创建一个学生对象,属性有name,number,class,sex,age,school等属性,如果每一个属性都可以为空,也就是说我们可以只用一个name,也可以用一个school,name,或者一个class,number,或者其他任意的赋值来创建一个学生对象,这时该怎么构造?

  难道我们写6个1个输入的构造函数,15个2个输入的构造函数.......吗?这个时候就需要用到Builder模式了。给个例子,大家肯定一看就懂:

public class Builder {

    static class Student{
        String name = null ;
        int number = -1 ;
        String sex = null ;
        int age = -1 ;
        String school = null ;
     //构建器,利用构建器作为参数来构建Student对象
        static class StudentBuilder{
            String name = null ;
            int number = -1 ;
            String sex = null ;
            int age = -1 ;
            String school = null ;
            public StudentBuilder setName(String name) {
                this.name = name;
                return  this ;
            }

            public StudentBuilder setNumber(int number) {
                this.number = number;
                return  this ;
            }

            public StudentBuilder setSex(String sex) {
                this.sex = sex;
                return  this ;
            }

            public StudentBuilder setAge(int age) {
                this.age = age;
                return  this ;
            }

            public StudentBuilder setSchool(String school) {
                this.school = school;
                return  this ;
            }
            public Student build() {
                return new Student(this);
            }
        }

        public Student(StudentBuilder builder){
            this.age = builder.age;
            this.name = builder.name;
            this.number = builder.number;
            this.school = builder.school ;
            this.sex = builder.sex ;
        }
    }

    public static void main( String[] args ){
        Student a = new Student.StudentBuilder().setAge(13).setName("LiHua").build();
        Student b = new Student.StudentBuilder().setSchool("sc").setSex("Male").setName("ZhangSan").build();
    }
}

6.适配器模式(Adapter)

适配器模式的作用就是在原来的类上提供新功能。主要可分为3种:

//target 目标

public interface ThreeInterface {
 
    public void OfferPowerForThree(); //三个口的插头有 一 个 功能,能够为三个触角的插头提供电源
 
}

需要被适配者,也就是两个触角的插头

package Adapter;
 
public interface TwoInterface {
 
    public void OfferPowerForTwo();//两个口的插头有一个功 能,能够为两个触角的插头提供电源
}
 
实现:
 
package Adapter;
 
public class RealTwo implements TwoInterface{
 
    @Override
    public void OfferPowerForTwo() {
        // TODO Auto-generated method stub
        System.out.println("我可以为两个触角的插头提供电源!");
 
    }
 
}
 

需要一个适配器


public class ThreeToTwoAdapter implements ThreeInterface {
 
    TwoInterface twoInterface;
 
    public ThreeToTwoAdapter(TwoInterface twoInterface)
    {
        this.twoInterface=twoInterface;
    }
 
    @Override
    public void OfferPowerForThree() {
        // TODO Auto-generated method stub
        twoInterface.OfferPowerForTwo();
    }
 
}

需要一个场景,这个场景下面,没有被是适配者可以直接用的资源,需要适配器进行转换,在上面的例子中也就是有一个两个触角的插头三十没用可以用的两个口的插座。

 

public class Test {
 
    //现在这快地方只有 三个口 的 插 座 ,但是插头是两个触角的,需要一个适配器
 
    public static void main(String []args)
    {
        //1、熟悉定义一个两个触角的插头,这个是本来自带的
 
        TwoInterface twoInterface=new RealTwo();
 
        //2、定义一个适配器,使得三个口的插座可以为两个触角的插头提供电源
        ThreeInterface threeInterface=new ThreeToTwoAdapter(twoInterface);
 
        //3、提供电源
        threeInterface.OfferPowerForThree();
 
    }
 
}
 

 

7.装饰模式(Decorator)参考 https://www.jianshu.com/p/c26b9b4a9d9e

动态的给对象添加一些额外的属性或行为。相比于使用继承,装饰者模式更加灵活。

在装饰模式中的各个角色有:
  (1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
  (2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
  (3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
  (4)具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。

//定义组件类,也是装饰者和被装饰者的超类Sweet .java
public abstract class Sweet {
    String description = "Sweet";

    public String getDescription() {
        return description;
    }

    public abstract double cost();
}

//定义被装饰者蛋糕类,Cake .java
public class Cake extends Sweet {
    @Override
    public String getDescription() {
        return "一个蛋糕";
    }

    @Override
    public double cost() {
        return 66;
    }
}

//定义抽象装饰者类Decorator.java
public abstract class Decorator extends Sweet {
    public abstract String getDescription();
}

//定义具体装饰者水果类,FruitDecorator.java:
public class FruitDecorator extends Decorator {
    Sweet sweet;

    public FruitDecorator(Sweet sweet) {
        this.sweet = sweet;
    }

    @Override
    public String getDescription() {
        return sweet.getDescription() + ",水果";
    }

    @Override
    public double cost() {
        return sweet.cost() + 10;
    }
}

//定义具体装饰者蜡烛类,CandleDecorator.java
public class CandleDecorator extends Decorator {
    Sweet sweet;

    public CandleDecorator(Sweet sweet) {
        this.sweet = sweet;
    }

    @Override
    public String getDescription() {
        return sweet.getDescription() + ",蜡烛";
    }

    @Override
    public double cost() {
        return sweet.cost() + 10;
    }
}

//测试
public static void main(String[] args) {

    Cake cake = new Cake();
    System.out.println(cake.getDescription() + "总共花费" + cake.cost());

    FruitDecorator fruitDecorator = new FruitDecorator(cake);
    System.out.println(fruitDecorator.getDescription() + "总共花费" + fruitDecorator.cost());

    CandleDecorator candleDecorator = new CandleDecorator(fruitDecorator);
    System.out.println(candleDecorator.getDescription() + "总共花费" + candleDecorator.cost());

}

8.代理模式(Proxy)

客户端通过代理类访问,代理类实现具体的实现细节,客户只需要使用代理类即可实现操作。

为什么要采用这种间接的形式来调用对象呢?一般是因为客户端不想直接访问实际的对象,或者访问实际的对象存在困难,因此通过一个代理对象来完成间接的访问。比如请一个律师代理来打官司。

静态代理

public interface Subject {
    void visit();
}


public class RealSubject implements Subject {

    private String name = "byhieg";
    @Override
    public void visit() {
        System.out.println(name);
    }
}


public class ProxySubject implements Subject{

    private Subject subject;

    public ProxySubject(Subject subject) {
        this.subject = subject;
    }

    @Override
    public void visit() {
        subject.visit();
    }
}

//测试
public class Client {

    public static void main(String[] args) {
        ProxySubject subject = new ProxySubject(new RealSubject());
        subject.visit();
    }
}

各大框架都喜欢的动态代理

动态代理有别于静态代理,是根据代理的对象,动态创建代理类。这样,就可以避免静态代理中代理类接口过多的问题。动态代理是实现方式,是通过反射来实现的,借助Java自带的java.lang.reflect.Proxy,通过固定的规则生成。
其步骤如下:

  1. 编写一个委托类的接口,即静态代理的(Subject接口)
  2. 实现一个真正的委托类,即静态代理的(RealSubject类)
  3. 创建一个动态代理类,实现InvocationHandler接口,并重写该invoke方法
  4. 在测试类中,生成动态代理的对象。

第一二步骤,和静态代理一样,不过说了。第三步,代码如下:

public class DynamicProxy implements InvocationHandler {
    private Object object;
    public DynamicProxy(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(object, args);
        return result;
    }
}

//测试
public class Client {

    public static void main(String[] args) {
        Subject realSubject = new RealSubject();
        DynamicProxy proxy = new DynamicProxy(realSubject);
        ClassLoader classLoader = realSubject.getClass().getClassLoader();
        Subject subject = (Subject) Proxy.newProxyInstance(classLoader, new  Class[]                        {Subject.class}, proxy);
        subject.visit();
    }
}

 

 

 

 

如何用capl操控程控电源(RS232) capl脚本操控RS232 阅读详情

相关推荐

手把手拆解DGX GB200 NVL72:1个机柜如何塞进72块GPU?详解NVLink Switch铜缆背板设计

本文深度解析英伟达DGX GB200 NVL72系统如何通过NVLink Switch铜缆背板设计,在标准42U机柜中集成72块B200 GPU,实现1800GB/s的超高带宽。文章详细介绍了模块化架构、铜缆互连技术、液冷散热方案和高密度供电系统等核心创新,为AI算力需求提供突破性解决方案。

red88的博客 1636

Sweet-API基于Java的HTTP API快速接口开发框架

基于Java的HTTP API快速接口开发框架,线上完成接口开发、调试和发布,自动映射为HTTP接口

qq_33785771的博客 556

HFSS15 win10_64位破解

HFSS15 win10_64位破解 找到的别人的软件,但在首次安装时失败了,并不能patched。寻找了几种方法,已成功安装。在此写下安装经验,供大家参考。 软件安装包以及破解软件: 链接:https://pan.baidu.com/s/1MMjV_31maU5QD6fmI4zfIA 提取码:yj4q 在安装之前,建议关闭杀毒软件。 Step1:进入HFSS150Win64安装包,点击au...

玉笙寒 4万+

JAVA 入门

JAVA 入门 一、常见的DOS命令 1.进入环境 ​ 进入方式: ​ (1)在搜索框搜索命令提示符,直接进入 ​ ​ (2)快捷键:window+r,在弹出的运行框输入cmd进入。 2.常用命令 (1)盘符的切换: ​ 盘符名+冒号 再回车(例如:d:)盘符名大小写都行 (2)切换路径: ​ cd 路径(中间加空格) ​ 在同一文件夹下可以使用相对路径或者绝对路径;如果要找的文...

weixin_44264545的博客 387

AT32F403A ADC通道管理与转换模式实战解析

本文深入解析AT32F403A微控制器的ADC模块,重点阐述其通道管理机制与四种转换模式(序列模式、抢占自动转换模式、反复模式、分割模式)的实战应用。通过详细的配置步骤与代码示例,帮助开发者高效实现模拟数字转换,优化数据采集性能与系统响应。

sky77的博客 284

Kali Linux渗透测试:蚁剑(AntSword)三种安装方法与避坑指南

WebShell管理是渗透测试与网络安全攻防演练中的关键技术环节,它允许安全人员在获得初步访问权限后,对目标系统进行文件管理、命令执行和数据库操作等深度控制。其核心原理是通过在Web服务器上植入特定脚本,建立一条隐蔽的远程管理通道。在实战中,一个高效、稳定的WebShell管理工具能极大提升后渗透阶段的工作效率与成功率。蚁剑(AntSword)作为一款功能强大的国产开源工具,凭借其插件化架构和图形化界面,成为众多安全研究人员的首选。本文将聚焦于如何在渗透测试专用操作系统Kali Linux上部署蚁剑,详细对

weixin_34413103的博客 421

Java Web 框架的“甜点”

Jave Web Framework Sweet Spots Java Web 框架的“甜点” 这是一篇很有趣的文档,所以摘要一下,其实类似阅读笔记,好像是3/25发布的: 不知怎么翻译Sweet Spots,难道翻译为甜处、甜头、蜜点、蜜穴? 这时基于对以下人的采访:JSF  Jacob Hook...

Tin 3781

基于TL431与MOSFET的高效过压保护电路设计详解

本文详细解析了基于TL431与MOSFET的高效过压保护电路设计。通过TL431精准监测电压,驱动MOSFET作为主开关,实现快速可靠的电源保护。文章涵盖电路原理、参数计算、性能优化及实战调试要点,为电子设备提供了一套经典且成本低廉的过压保护解决方案。

weixin_29215391的博客 803

大聪明教你学Java | Hutool - A set of tools that keep Java sweet

前言 无论在开发什么项目,我们都会用到N多种工具类,DateUtils、FileUtils、StringUtils等等… 开发一个新项目就需要把这些“轮子”复制一次,虽然只是Ctrl+C/V,但是也麻烦了一些,而且也会让我们的Utils包显得贼臃肿???? 那么怎么解决这个问题呢?稍安勿躁,接下来就该请我们的主角闪亮登场了(●’◡’●) —— Hutool - A set of tools that keep Java sweet 在Hutool官网中有这么一段话: Hutool是一个小而全的Java工具类

不肯过江东丶 1万+

[P4V]Perforce(P4V)使用教程

1.前言 Perforce SCM System是一款构建于可伸缩客户/服务器结构之上的软件配置管理工具。仅仅应用TCP/IP,开发人员就能够通过多种Perforce客户端(几种平台的GUI、WEB、或命令行)访问Perforce服务器。Perforce能够被快速和容易地部署,即使对大型或分布式的站点,也只要求最小限度的管理。Perforce可以使用在50多个操作系统中,它包括版...

元直的博客 2万+

深度强化学习在机器人控制中的应用

非常感谢您提供如此详细的任务要求和约束条件。作为一位世界级的人工智能专家和计算机领域大师,我将全身心投入到这篇技术博客的撰写中。 深度强化学习在机器人控制中的应用 1. 背景介绍 近年来,随着人工智能技术的飞速发展,深度学习和强化学习在各个领域都得到了广泛应用,尤其是在机器人

AI天才研究院 1328

Java七种常用设计模式

抽象工厂模式(Abstract Factory Pattern)是Java中常用的一种创建型设计模式,它提供了一种创建一系列相关或相互依赖的对象接口,而无需指定它们具体的类。抽象工厂模式和工厂方法模式类似,不同之处在于抽象工厂模式中工厂类不单独生产一种产品,而是生产一系列相关的产品。定义抽象产品类:void use();定义具体产品类:System . out . println("使用ProductA1");System . out . println("使用ProductA2");

qq_45196093的博客 2万+

⭐️【2024年新版教程】vmware tools安装步骤(Windows、Linux、MacOS版本)

VMware Tools是VMware提供的一套实用工具,它可以增强虚拟机与宿主机之间的交互性能,如改进显示性能、优化鼠标和键盘性能、提供时间同步功能等。无论是在Windows、Linux还是MacOS虚拟机上,安装VMware Tools都可以提高虚拟机的使用体验。以上就是在不同操作系统上安装VMware Tools的步骤,希望对您有所帮助。

Python老吕的博客 6万+

Java中几种常用的设计模式

在Java的学习中比较常见的几种设计模式 尚学堂-马士兵老师大致讲的,总结一下 1.单例模式(单态模式): 在程序运行过程中只有几个类或是只有一个类,达到“单例模式”。无论外部类调用多少次“构造”,内存中只是分配一次实例化的对象,达到单例模式。外部不能创建对象,所以必须在原来内部创建对象,以备外部调用。由于外面没有创建对象的情况下,只能反问static 方法,故返回创建的

刘新宇的博客 3014

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

深度学习工具包 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常用设计模式有几种?想必java小白对这个问题也感到疑惑。这个问题千锋重庆java培训机构的小编就来告诉大家。 单例模式 简单点说,就是一个应用程序中,某个类的实例对象只有一个,你没有办法去new,因为构造器是被private修饰的,一般通过getInstance()的方法来获取它们的实例。 getInstance()的返回值是一个对象的引用,并不是一个新的实例,所以不要错误的理解成多个对象。单例模式实现起来也很容易,直接看demo吧。 public class Singleton { priv

qf2019的博客 166

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

你知道 的Java中常用的几种设计模式

接着,我们创建一个日志记录器工厂(LoggerFactory),它负责根据传入的参数或配置来创建并返回相应的日志记录器实例。再举例个实用的例子,它涉及到创建一个日志记录器的工厂,该工厂可以根据不同的配置或参数返回不同类型的日志记录器实例。类中添加相应的逻辑来创建并返回新的日志记录器实例,而不需要修改客户端代码,从而实现了对扩展的开放和对修改的封闭(开闭原则)。,该方法接收一个字符串参数(表示日志记录器的类型),并根据这个参数返回相应的日志记录器实例。:确保一个类只有一个实例,并提供一个全局访问点。

w1990xw的博客 1609

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

Java 中几种常用设计模式

Java 中一般认为有23种设计模式,当然暂时不需要所有的都会,但是其中常见的几种设计模式应该去掌握。 总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。 行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模...

apriaaaa的博客 226

Java常用的几种设计模式

  本来想写点spring相关的东西的,想来想去,先写点设计模式的东西吧   什么是设计模式?套用百度百科的话解释吧   设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。使用设计模式的目的:为了代码可重用性、让代码更容易被他人理解、保证代码可靠性。 设计模式使代码编写真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。   这...

weixin_30369041的博客 185

java中常用到得设计模式有哪几种?

java中常用到得设计模式有哪几种? 2012-02-14 20:48匿名|分类:JAVA相关| 浏览20282次 分享到: 2012-02-15 09:55提问者采纳 答题闯关,过关即送礼!快来参加~ 一共23种设计模式! 按照目的来分,设计模式可以分为创建型模式、结构型模式和行为型模式。 创建型模式用来处理对象的创建过程;结构型

u013305082的专栏 571

Java几种常用的设计模式

设计模式是程序设计的一些通用模式,掌握了设计模式可以快速将复杂的程序进行抽象化,增加程序的可理解性,复用性以及健壮性。设计模式代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。 下面介绍几种常用的设计模式: 1.工厂模式 工厂模式(Factory P...

qq_17184049的博客 375

java中几种常用的设计模式

java中常用的几种设计模式: 创建型:简单工厂模式(并不是23种设计模式之一)、工厂方法、抽象工厂模式、单例模式、生成器模式和原型模式结构型:适配器模式adapter、桥接模式bridge、组合器模式component、装饰器模式decorator、门面模式、亨元模式flyweight和代理模式proxy行为型:命令模式command、解释器模式、迭代器模式、中介者模式、备忘录模式、观

jiyang_1的博客 1万+

java几种常用的设计模式

今天说说几种常见的设计模式,写个博客,记录一下。 首先,啥叫设计模式呢? 设计模式是一套被反复使用、多数人知晓的、经过分类编码、代码设计经验的总结。举个例子,把编码比喻成打仗,那么设计模式就是孙子兵法三十六计。设计模式的目的是为了可重用代码、让代码更容易被他人理解、保证代码的可靠性。 单例模式 作用是保证整个应用程序代码中某个实例有且仅有一个。 分为饿汉模式和懒汉模式 区别:饿汉模式的特点是加载类...

Jacy_Wang的博客 744

Java中几种常用设计模式

一、介绍 设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。 二、设计模式分类 创建型模式,五种,即工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式,:七种,即适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。 行为型模式,...

~~~的博客 328
上一篇: JVM核心之JVM运行和类加载全过程
下一篇: 解读什么是Redis缓存穿透、缓存雪崩和缓存击穿
qq_31459039
博客等级 码龄11年 52粉丝 81原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值