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. JQuery局部刷新与全页面刷新

    局部刷新: 这个方法就多了去了,常见的有以下几种: $.get方法,$.post方法,$.getJson方法,$.ajax方法如下 前两种使用方法基本上一样 $.get(”Default.php”, ...

  2. Jupyter notebook 和 Jupyter lab 的区别

    Jupyter Notebook Jupyter Notebook 是一个款以网页为基础的交互计算环境,可以创建Jupyter的文档,支持多种语言,包括Python, Julia, R等等.广泛用于数 ...

  3. fscanf的用法

    fscanf用于读取字符串数据流,遇到空白字符(空格' '; 制表符'\t'; 新行符'\n')就停止,若要读取完整的一行数据,可以使用格式控制("%[^\n]%*c"),或者使用 ...

  4. 5314跳跃游戏IV

    题目:给你一个整数数组 arr ,你一开始在数组的第一个元素处(下标为 0).每一步,你可以从下标 i 跳到下标:    i + 1 满足:i + 1 < arr.length    i - 1 ...

  5. OVERVIEW:gcc,g++,cmake,make

    首先介绍一下GCC:GNU Compiler Collection(GNU 编译器集合),在为Linux开发应用程序时,绝大多数情况下使用的都是C语言,因此几乎每一位Linux程序员面临的首要问题都是 ...

  6. postman测试

    Postman接口性能测试 1.从文件中获取参数,然后点击Runner 2.勾选测试用例,配置用例次数.参数文件.返回data等 3.点击run 测试用例 4.查看测试结果 5.测试接口:https: ...

  7. bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

    ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL ...

  8. 再来看看Java的新特性——其他新特性

    关于剩余Java8新特性知识点总结,包含:默认方法.Optional.CompletableFuture.时间相关. 默认方法 默认方法皆在帮助Java新功能可以兼容低版本JDK已开发的程序. 比如说 ...

  9. Regex: positive lookahead 先行断言____ 后行断言(lookbehind)

    先行断言: /a(?=b)/  ,positive lookahead,a的后方必须是b才行 /a(?!b)/   ,negative lookahead,a的后方必须不是b才能匹配 如下图示:  来 ...

  10. Cobbler_自动装系统

    Cobbler —自动装系统的操作步骤 Cobbler是一款自动化操作系统安装的实现,与PXE安装系统的区别就是可以同时部署多个版本的系统,而PXE只能选择一种系统. Cobbler 的安装 # 在一 ...