文档章节

Thinking in Patterns #1: The pattern concept

LuXing
 LuXing
发布于 2014/06/10 20:16
字数 889
阅读 62
收藏 2

#Thinking in Patterns
##1: The pattern concept
###What is a pattern?
Initially, you can think of a pattern as an especially clever and insightful way of solving a particular class of problems.
###Pattern taxonomy
After some pondering, I’ve come up with a sort of hierarchy describing a succession of different types of categories:

    1. Idiom: how we write code in a particular language to do this particular type of thing. This could be something as common as the way that you code the process of stepping through an array in C (and not running off the end).
    1. Specific Design: the solution that we came up with to solve this particular problem. This might be a clever design, but it makes no attempt to be general.
    1. Standard Design: a way to solve this kind of problem. A design that has become more general, typically through reuse.
  1. Design Pattern: how to solve an entire class of similar problem. This usually only appears after applying a standard design a number of times, and then seeing a common pattern throughout these applications .

###The singleton
Possibly the simplest design pattern is the singleton, which is a way to provide one and only one object of a particular type. This is used in the Java libraries, but here’s a more direct example:

//: c01:SingletonPattern.java
// The Singleton design pattern: you can
// never instantiate more than one.
// Since this isn't inherited from a Cloneable
// base class and cloneability isn't added,
// making it final prevents cloneability from
// being added through inheritance:
final class Singleton {
private static Singleton s = new Singleton(47);
private int i;
private Singleton(int x) { i = x; }
public static Singleton getReference() {
return s;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}
public class SingletonPattern {
public static void main(String[] args) {
Singleton s = Singleton.getReference();
System.out.println(s.getValue());
Singleton s2 = Singleton.getReference();
s2.setValue(9);
System.out.println(s.getValue());
try {
// Can't do this: compile-time error.
// Singleton s3 = (Singleton)s2.clone();
} catch(Exception e) {
e.printStackTrace(System.err);
}
}
} ///:~

The key to creating a singleton is to prevent the client programmer from having any way to create an object except the ways you provide. You must make all constructors private, and you must create at least one constructor to prevent the compiler from synthesizing a default constructor for you (which it will create as “friendly”).
At this point, you decide how you’re going to create your object. Here, it’s created statically, but you can also wait until the client programmer asks for one and create it on demand. In any case, the object should be stored privately. You provide access through public methods. Here, getReference( ) produces the reference to the Singleton object. The rest of the interface (getValue( ) and setValue( )) is the regular class interface.
Java also allows the creation of objects through cloning. In this example, making the class final prevents cloning. Since Singleton is inherited directly from Object, the clone( ) method remains protected so it cannot be used (doing so produces a compile-time error). However, if you’re inheriting from a class hierarchy that has already overridden clone( ) as public and implemented Cloneable, the way to prevent cloning is to override clone( ) and throw a CloneNotSupportedException as described in Appendix A. (You could also override clone( ) and simply return this, but that would be deceiving since the client programmer would think they were cloning the object, but would instead still be dealing with the original.)
Note that you aren’t restricted to creating only one object. This is also a technique to create a limited pool of objects. In that situation, however, you can be confronted with the problem of sharing objects in the pool. If this is an issue, you can create a solution involving a check-out and check-in of the shared objects.

###Classifying patterns
The Design Patterns book discusses 23 different patterns, classified under three purposes (all of which revolve around the particular aspect that can vary). The three purposes are:
* 1. Creational: how an object can be created. This often involves isolating the details of object creation so your code isn’t dependent on what types of objects there are and thus doesn’t have to be changed when you add a new type of object. The aforementioned Singleton is classified as a creational pattern, and later in this book you’ll see examples of Factory Method and Prototype.  

    1. Structural: designing objects to satisfy particular project constraints. These work with the way objects are connected with other objects to ensure that changes in the system don’t require changes to those connections.
    1. Behavioral: objects that handle particular types of actions within a program. These encapsulate processes that you want to perform, such as interpreting a language, fulfilling a request, moving through a sequence (as in an iterator), or implementing an algorithm. This book contains examples of the Observer and the Visitor patterns.

###Exercises

    1. SingletonPattern.java always creates an object, even if it’s never used. Modify this program to use lazy initialization, so the singleton object is only created the first time that it is needed.
    1. Using SingletonPattern.java as a starting point, create a class that manages a fixed number of its own objects. Assume the objects are database connections and you only have a license to use a fixed quantity of these at any one time.

© 著作权归作者所有

共有 人打赏支持
上一篇: 资源管理
LuXing
粉丝 19
博文 84
码字总数 54768
作品 0
广州
程序员
私信 提问
Thinking, Consciousness and a Model of Intelligence

Introduction At the time I write this article, December 2017, I couldn't find a similar approach in the public space. There are a lot of descriptions of the neurons, going into ......

Adrian Pirvu
2017/12/20
0
0
git ls-files 显示当前文件状态

NAME git-ls-files - Show information about files in the index and the working tree SYNOPSIS git ls-files [-z] [-t] -v(-[c|d|o|i|s|u|k|m])[--eol][-x <pattern>|--exclude=<pattern>......

Oscarfff
2016/09/20
20
0
TCPMon—查看信息传输小工具

Content Content Introduction Structure and Dependencies Usage Patterns As an Explicit Intermediate As a Request Sender for Web Services As a Proxy Advanced Settings Slow Connect......

红焖鲤鱼
2015/09/11
348
0
nexus配置

一、配置文件位置 /home/tools/nexus/WEB-INF/classes/nexus.properties 二、找到sonatype-work目录 /root/sonatype-work 三、找到nexus配置文件 /root/sonatype-work/nexus/conf/nexus.xml......

nibilly
2016/07/27
21
0
PostgreSQL中时间转换

The PostgreSQL formatting functionsprovide a powerful set of tools for converting various data types(date/time, integer, floating point, numeric) to formatted strings andfor con......

sucre
2016/02/18
285
0

没有更多内容

加载失败,请刷新页面

加载更多

数据库技术-Mysql主从复制与数据备份

数据库技术-Mysql 主从复制的原理: MySQL中数据复制的基础是二进制日志文件(binary log file)。一台MySQL数据库一旦启用二进制日志后,其作为master,它的数据库中所有操作都会以“事件”...

须臾之余
昨天
6
0
Git远程仓库——GitHub的使用(一)

Git远程仓库——GitHub的使用(一) 一 、 Git远程仓库 由于你的本地仓库和GitHub仓库之间的传输是通过SSH加密的,所以需要一下设置: 步骤一、 创建SSH key 在用户主目录下,看看有没有.ss...

lwenhao
昨天
1
0
SpringBoot 整合

springBoot 整合模板引擎 SpringBoot 整合Mybatis SpringBoot 整合redis SpringBoot 整合定时任务 SpringBoot 整合拦截器...

细节探索者
昨天
0
0
第二个JAVA应用

第二个JAVA应用 方法一:配置文件: # cd /usr/local/tomcat/conf/# vim server.xml</Host> <Host name="www.wangzb.cc" appBase="/data/wwwroot/www.wangzb.cc" //引用所......

wzb88
昨天
0
0
2019年阿里Java面试必问:JVM与性能优化+Redis+设计模式+分布式

前言 一年之计在于春 金三银四已经要到来,2019的新的开始,作为一个开发人员,你是否面上了自己理想的公司,薪资达到心中理想的高度? 面试:如果不准备充分的面试,完全是浪费时间,更是对...

火力全開
昨天
14
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部