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. echars 柱状图点击事件

     drawlineCRK() {       let _this = this;       ///绘制echarts 柱状图       let mycharts = this.$echarts.i ...

  2. c#学习笔记04——ADO.NET

    ADO.NET结构:ADO.NET建立在几个核心类之上,这些类可以分为两组 包含和管理数据的类:DataSet DataTable DataRow DataRelation... 链接数据源的类:Co ...

  3. ZJNU 2208 - 你渴望力量吗

    在图的最外面套一层0(防止到头) 然后搜索图有多少块在 '0'有两块0,一块1 '1'有一块0,一块1 其余情况不存在 #include<stdio.h> ],dx[]={,,,-},dy ...

  4. 小白学习之pytorch框架(3)-模型训练三要素+torch.nn.Linear()

    模型训练的三要素:数据处理.损失函数.优化算法    数据处理(模块torch.utils.data) 从线性回归的的简洁实现-初始化模型参数(模块torch.nn.init)开始 from torc ...

  5. Django整体架构

    Django整体架构 用户能够访问到的所有的资源 都是程序员提前暴露好的, 如果没有暴露 用户就永远访问不了 用户能够访问到的所有的资源 都是程序员提前暴露好的, 如果没有暴露 用户就永远访问不了 一 ...

  6. RSAUtils加密解密

    import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import javax.cr ...

  7. [TJOI2017]不勤劳的图书管理员(分块+树状数组)

    有一个数组开大会MLE开小会RE的做法:就是树套树,即树状数组套主席树,这种方法比较暴力,然而很遗憾它不能通过,因为其时空复杂度均为O(nlog2n). 想到一种不怎么耗内存,以时间换空间,分块!单次 ...

  8. 上传excel文件,读取内容,增加事务写入数据库

    package com.inspur.icpmg.itss.asset.dao.impl; import com.inspur.icpmg.util.DBHelper; import org.apac ...

  9. Canal —— 基本概念及使用

    参考文档 开源数据同步神器--canal [若泽大数据]大数据之实时数据源同步中间件--生产上Canal与Maxwell颠峰对决

  10. 如何写JS库,JS库写法

    前言: 现在javascript库特别多,其写法各式各样,总结几种我们经常见到的,作为自己知识的积累.而目前版本的 JavaScript 并未提供一种原生的.语言级别的模块化组织模式,而是将模块化的方 ...