1、Factory Design pattern

工厂设计模式的优点

(1)工厂设计模式提供了接口而不是实现的代码方法。

(2)工厂模式从客户端代码中删除实际实现类的实例化。工厂模式使我们的代码更健壮,耦合更少,易于扩展。例如,我们可以轻松更改PC类实现,因为客户端程序不知道这一点。

(3)工厂模式通过继承提供实现和客户端类之间的抽象。

JDK中工厂设计模式实列

java.util.Calendar,ResourceBundle和NumberFormat getInstance()方法使用Factory模式。

valueOf() 包装类中的方法,如Boolean,Integer等。

代码示例:https://github.com/journaldev/journaldev/tree/master/java-design-patterns/Factory-Design-Pattern

2、Prototype example

Employees.java

 package com.journaldev.design.prototype;

 import java.util.ArrayList;
import java.util.List; public class Employees implements Cloneable{ private List<String> empList; public Employees(){
empList = new ArrayList<String>();
} public Employees(List<String> list){
this.empList=list;
}
public void loadData(){
//read all employees from database and put into the list
empList.add("Pankaj");
empList.add("Raj");
empList.add("David");
empList.add("Lisa");
} public List<String> getEmpList() {
return empList;
} @Override
public Object clone() throws CloneNotSupportedException{
List<String> temp = new ArrayList<String>();
for(String s : this.getEmpList()){
temp.add(s);
}
return new Employees(temp);
} }

PrototypePatternTest.java

 package com.journaldev.design.test;

 import java.util.List;

 import com.journaldev.design.prototype.Employees;

 public class PrototypePatternTest {

     public static void main(String[] args) throws CloneNotSupportedException {
Employees emps = new Employees();
emps.loadData(); //Use the clone method to get the Employee object
Employees empsNew = (Employees) emps.clone();
Employees empsNew1 = (Employees) emps.clone();
List<String> list = empsNew.getEmpList();
list.add("John");
List<String> list1 = empsNew1.getEmpList();
list1.remove("Pankaj"); System.out.println("emps List: "+emps.getEmpList());
System.out.println("empsNew List: "+list);
System.out.println("empsNew1 List: "+list1);
} }

结果:

emps List: [Pankaj, Raj, David, Lisa]
empsNew List: [Pankaj, Raj, David, Lisa, John]
empsNew1 List: [Raj, David, Lisa]

3、Proxy模式

Proxy Design Pattern – Main Class

CommandExecutor.java

 package com.journaldev.design.proxy;

 public interface CommandExecutor {

     public void runCommand(String cmd) throws Exception;
}

CommandExecutorImpl.java

 package com.journaldev.design.proxy;

 import java.io.IOException;

 public class CommandExecutorImpl implements CommandExecutor {

     @Override
public void runCommand(String cmd) throws IOException {
//some heavy implementation
Runtime.getRuntime().exec(cmd);
System.out.println("'" + cmd + "' command executed.");
} }

Proxy Design Pattern – Proxy Class

CommandExecutorProxy.java

 package com.journaldev.design.proxy;

 public class CommandExecutorProxy implements CommandExecutor {

     private boolean isAdmin;
private CommandExecutor executor; public CommandExecutorProxy(String user, String pwd){
if("Pankaj".equals(user) && "J@urnalD$v".equals(pwd)) isAdmin=true;
executor = new CommandExecutorImpl();
} @Override
public void runCommand(String cmd) throws Exception {
if(isAdmin){
executor.runCommand(cmd);
}else{
if(cmd.trim().startsWith("rm")){
throw new Exception("rm command is not allowed for non-admin users.");
}else{
executor.runCommand(cmd);
}
}
} }

ProxyPatternTest.java

 package com.journaldev.design.test;

 import com.journaldev.design.proxy.CommandExecutor;
import com.journaldev.design.proxy.CommandExecutorProxy; public class ProxyPatternTest { public static void main(String[] args){
CommandExecutor executor = new CommandExecutorProxy("Pankaj", "wrong_pwd");
try {
executor.runCommand("ls -ltr");
executor.runCommand(" rm -rf abc.pdf");
} catch (Exception e) {
System.out.println("Exception Message::"+e.getMessage());
} } }

output

'ls -ltr' command executed.
Exception Message::rm command is not allowed for non-admin users.

4、Singleton模式

(1)Singleton模式限制了类的实例化,并确保java虚拟机中只存在该类的一个实例。

(2)单例类必须提供一个全局访问点来获取类的实例。

(3)单例模式用于日志记录 ,驱动程序对象,缓存和线程池

(4)Singleton设计模式也用于其他设计模式,如Abstract FactoryBuilderPrototypeFacade等。

Singleton设计模式也用于核心java类,例如java.lang.Runtimejava.awt.Desktop

Java Singleton模式

为了实现Singleton模式,我们有不同的方法,但它们都有以下常见概念。

(1)私有构造函数,用于限制其他类的实例化。

(2)同一类的私有静态变量,它是该类的唯一实例。

(3)返回类实例的公共静态方法,这是外部世界获取单例类实例的全局访问点。

参考链接:https://www.journaldev.com/1827/java-design-patterns-example-tutorial

Java Design Patterns(2)的更多相关文章

  1. Java面试宝典(7)混合2

    数据库 & XML & 流行的框架与新技术 & 软件工程与设计模式 & J2EE & EBJ & webservice & 其他 pageSiz ...

  2. [译文]Domain Driven Design Reference(一)—— 前言

    本书是Eric Evans对他自己写的<领域驱动设计-软件核心复杂性应对之道>的一本字典式的参考书,可用于快速查找<领域驱动设计>中的诸多概念及其简明解释. DDD到目前为止知 ...

  3. Java Learning Path(三)过程篇

    Java Learning Path(三)过程篇 每个人的学习方法是不同的,一个人的方法不见得适合另一个人,我只能是谈自己的学习方法.因为我学习Java是完全自学的,从来没有问过别人,所以学习的过程基 ...

  4. Java 经典入门(一)

    一.什么是 Java 技术?为何需要 Java? Java 是由 Sun Microsystems 在 1995 年首先发布的编程语言和计算平台.有许多应用程序和 Web 站点只有在安装 Java 后 ...

  5. 数组和链表--Java学习笔记(一)

    版权声明: 本文由Faye_Zuo发布于http://www.cnblogs.com/zuofeiyi/, 本文可以被全部的转载或者部分使用,但请注明出处. 我是一个全职妈妈,两年前在上海一家人力资源 ...

  6. Java学习笔记(04)

    Java学习笔记(04) 如有不对或不足的地方,请给出建议,谢谢! 一.对象 面向对象的核心:找合适的对象做合适的事情 面向对象的编程思想:尽可能的用计算机语言来描述现实生活中的事物 面向对象:侧重于 ...

  7. java基础知识(四)java内存机制

    Java内存管理:深入Java内存区域 上面的文章对于java的内存管理机制讲的非常细致,在这里我们只是为了便于后面内容的理解,对java内存机制做一个简单的梳理. 程序计数器:当前线程所执行的字节码 ...

  8. 《java小应用程序(Applet)和java应用程序(Application)分别编写的简单计算器》

    Application和Java Applet的区别.Java语言是一种半编译半解释的语言.Java的用户程序分为两类:Java Application和Java Applet.这两类程序在组成结构和 ...

  9. 《Java应用程序(Application)》

    在编写Java应用程序(Application)时可以这样: 1,定义包名. 2, 导入相关的包. 3, 定义一个类. 4,定义相关变量. 5,定义构造函数.(在构造函数内调用init()方法和add ...

随机推荐

  1. UML-领域模型-定义

    领域模型是OO分析中最重要和经典的模型(用例是重要的需求分析制品,但不是面向对象的).领域模型也是重点. 1.关系 2.例子 3.定义 领域模型没有定义方法的类图.只包括: 1).领域对象或概念类 2 ...

  2. 一个简单WebApp的全程

    开始前,我先给出上一篇选项卡的demo链接http://xqhuadou.com/demo1/index.html.相信看着应该很带感,不过这个是之前经过修改的. 制作过程我就不多说了,可以直接看源码 ...

  3. 01.Java安装及环境变量的设置

    1.下载 https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2.mac上安装及配 ...

  4. Java虚拟机(JVM) - 学习总结(全)

    深入理解java虚拟机---学习总结: 1.Java内存区域 1.1 java运行时数据区 Java 虚拟机所管理的内存如下图所示,基于JDK1.6. 基于jdk1.8画的JVM的内存模型 (1) 程 ...

  5. 蓝桥杯 乘积最大(区间dp、数据水的话long long,暴力就能过)

    Description 今年是国际数学联盟确定的“2000——世界数学年”,又恰逢我国著名数学家华罗庚先生诞辰90周年.在华罗庚先生的家乡江苏金坛,组织了一场别开生面的数学智力竞赛的活动,你的一个好朋 ...

  6. python 输入输出 条件判断 循环

    1.条件判断 score = int(input("请输入学生成绩:"))if score>100 and score <0: print("请输入正确的成绩 ...

  7. 模仿u-boot的makefile结构

    u-boot(2014.04)是通过顶层makefile调用各子目录中的makefile来实现整个工程的编译的,实际上子目录的makefile是include进来的.这里仿照这种结构写个模板测试一下. ...

  8. 阿里云 asp.net core nginx 单机部署

    1. dotnet core 安装 https://www.microsoft.com/net/download#core 安装之前要安装依赖:yum install libunwind libicu ...

  9. regex(python)

    正则表达式 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/26 16:39 # @Author : jackendoff ...

  10. British postal system to launch parcel postboxes

    1 单词 parcel n. 包裹 pilot n. 试行计划 2 句子 1400 of the new boxes will be installed at 30 locations across ...