Thinking in Patterns chapter 7: Encapsulating creation

Thinking in Patterns with Java V0.9: chapter 7: Encapsulating creation: TIPatterns.htm#_Toc41169712

1, The sections name of today's learning;

simple Factory method. 53

Polymorphic factories. 55

Abstract factories. 58

Exercises. 61

2, What is it talk about in these sections and my comments and feeling for the content:

Without the deeply thinking about the content of this chapter, and maybe I

have not many experience on program, I haven't known what matters I will meet

if creating object without "factory". But, I can see what it is talking about

in this chapter.

1), simple Factory method

The key of this pattern is a static factory method in base class can create

the objects of all kinds of sub classes according to the parameter passed into

this static factory method.

From the viewpoint of OOP, this method isn't a pure OO, because there are some

condictional testing in this method like below: 


    if(type.equals("Circle")) return new Circle();

    if(type.equals("Square")) return new Square();

Is there any way make this example more OO?

2), Polymorphic factories.

Just like Bruce's words in this section as below:


However, it seems that much of the time you

don?t need the intricacies of the polymorphic factory method, and a single

static method in the base class (as shown in ShapeFactory1.java) will work

fine.

After reading the example of this pattern, I can understand the base concept

of this pattern, I rewrite the process of this example with my own words

below:

Let's start from the main method, tracking the running step of this

example:

1>, suppose ShapeFactory.createShape("Circle"), and suppose no "Circle" in the

Map "factories" in abstract class ShapeFactory, the statement

[Class.forName("factory.shapefact2.Circle");] will create a class object

of class "factory.shapefact2.Circle", so the static block in this class will

process, here is below:


  static {

    ShapeFactory.addFactory(

      "Circle", new Factory());

  }

At this point, key-value pair: "Circle", instance object of Circle's inner class Factory which is a sub class of ShapeFactory has been puted into Map "factories";

2>, then, the statement below will create a "Circle" object and return it into

 the statement in main method:


return

      ((ShapeFactory)factories.get(id)).create();

In this way, we can add any number's new type without modifing any existed

code, even include the factory method in class ShapeFactory.

This is a real pure OO style objects creation schema just a little complex.

Maybe, I know the reason of GoF's "However, the Design Patterns book

emphasizes that the reason for the Factory Method pattern is so that different

types of factories can be subclassed from the basic factory (the above design

is mentioned as a special case)."

Maybe because GoF want come up with a pure OO factory schema, so they say that

the simple factory method is a special case of their "intricacies of the

polymorphic factory method", I think.

I feel that Bruce maybe prefer "simple factory method" than that "Polymorphic

factories" between his words. I think Bruce is a pragmatism master, if the

non-pure OO schema can resolve problem well, why to chose a more complex

implementation? just I think.

For me, if no enough reason for chosing a complex OO impelmentation, maybe I will chose that "simple factory method", at least, I can reduce many lines' coding. 

3), Abstract factories

The situation of applying this pattern in my mind maybe is below:

1>, There are several scene in the application;

2>, There are several class' object involved in every scene;

3>, The several class' object's composition is defferent from one scene to

another scene;

4>, So, every scene need a specific object factory;

5>, Create an Abstract factory is used as an interface of the specific object

factory above;

I haven't understood this pattern very clearly. If I meet some situations

future like above, I will remember this "Abstract factories" and will try its application too if I haven't forgotten this book.

3, My questions about the program itself;

1), The idea is that at the point of creation of the factory object, you decide how all the objects created by that factory will be used; 

2), The use of Abstract factories;

3), exercises;

4), what are there problems when creating objects in a real application without these factories pattern above?

4, My questions about the english language;

1), Strange words:

  sensible, chase down, matter, likely, suspect, happen to, presumably, sophisticated, intricacies, portability, Obstacle, Puzzle,

2), Strange sentences:

  1>,It happens to be the creation of the type that matters in this case rather than the use of the type (which is taken care of by polymorphism), but the effect is the same: adding a new type can cause problems.

  2>, If all the code in your program must go through this factory

whenever it needs to create one of your objects, then all you must do when you

add a new object is to modify the factory.

================================================================================

Example's uml class diagram reversed by ArgoUML0.22 (need some notion for these diagram, maybe I will do it future)

--------------------------------------------------------------------------------

Example:

//: factory:shapefact1:ShapeFactory1.java

// A simple static factory method.

*******************************************************************************

Example:

//: factory:shapefact2:ShapeFactory2.java

// Polymorphic factory methods.

********************************************************************************

Example:

//: factory:Games.java

// An example of the Abstract Factory pattern.



================================================================================

Thinking in Patterns chapter 6: Factoring commonality

Thinking in Patterns with Java V0.9: chapter 6: Factoring commonality: TIPatterns.htm#_Toc41169707

1, The sections name of today's learning;

Strategy: choosing the algorithm at run-time  48

Policy: generalized strategy. 50

Template method. 50

Exercises

2, What is it talk about in these sections and comments and feeling for the content:

  the “once and only once” principle, said at the begin of this chapter, I can't know it's meaning very clear, is it saying: do only one thing in a method?

  And, State, Strategy, Policy, Template method, it seems to me these four patterns has very similiar character, I can't distinguish them very clear.

  1), Strategy: choosing the algorithm at run-time

  However, I haven't find there is any difference bwteen State and Strategy now except their names.  class ServiceProvider in state:StateDemo.java just like class MinimaSolver in strategy:StrategyPattern.java, and so on.

  2), Policy: generalized strategy.

  No example in this section, it just says:"It also seems generally useful to distinguish Strategies with single methods from Policies with multiple methods."

  3), Template method.

  What is Template method?

  From my understanding, there exist two definitions : one is Template method Patterns; and another is a specific method in a base class, the mothod is usually called by the initialization method of this base class (I can't know if it is always called by that initialization method), this template method then call other methods in the base class to perform some actions, these performing real actions' methods can be overridden by the derived class.

  Although it says:"Note similarity with template method ? TM claims distinction that it has more than one method to call, does things piecewise. However, it?s not unlikely that strategy object would have more than one method call;" I can't feel there are too many similar places between State pattern and Template method pattern. Maybe, after reviewing this book, I will change my feeling a lot.

  I have found a bit difficult to learn this book, and write the diary in

english is a bit difficult too, if the difficult degree over my knowledge

scope a lot, maybe I will seek another resource to learn Design Patterns,

maybe a chinese book is better for me?

3, My questions about the program itself;

  1), Can't understand: Applying the "once and only once" principle produces the  most basic pattern of putting code that changes into a method.

  2), The difference between State and strategy pattern;

  3), Policy's example

  4), The difference between State and Template method.

4, My questions about the english language;

  1), Strange words:

  factoring commonality, similarity, piecewise, piecewise, shallowway, fulfullment, Policy, generalized, customs, undetermined,

  2), Strange sentences:

  1>, A fundamental concept in the application framework is the Template Method which is typically hidden beneath the covers and drives the application by calling the various methods in the base class (some of which you have overridden in order to create the application).

*****************************************************************************************************

//: strategy:StrategyPattern.java

//Strategy: choosing the algorithm at run-time

                                                      incomplete

JAVA操作数据库方式与设计模式应用(转帖)

呵呵,看起来是篇好文章啊。好文章是可遇而不可求的,不收藏,到时再去找就麻烦了。

转自:( JAVA操作数据库方式与设计模式应用http://www.javaresearch.org/article/58090.htm

                         JAVA操作数据库方式与设计模式应用

  jiqimiao1982 转贴   更新

  :2006-11-14 11:50:59  版

  本: 1.0  

  1.   在业务层使用JDBC直接操作数据库-最简单,最直接的操作

  1)数据库url,username,password写死在代码中

      Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

      String url="jdbc:oracle:thin:@localhost:1521:orcl";

      String user="scott";

      String password="tiger";

      Connection conn= DriverManager.getConnection(url,user,password); 

      Statement stmt=conn.createStatement(

  ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

      String sql="select * from test";

      ResultSet rs=stmt.executeQuery(sql);

  2)采用Facade和Command模式,使用DBUtil类封装JDBC操作;

        数据库url,username,password可以放在配置文件中(如xml,properties,ini等)。

        这种方法在小程序中应用较多。

  2.DAO(Data Accessor Object)模式-松耦合的开始

  DAO = data + accessor + domain object

  例如User类-domain object (javabean)

  UserDAO类-accessor ,提供的方法getUser(int id),save(User user)内包含了JDBC操

  作

  在业务逻辑中使用这两个类来完成数据操作。

  使用Factory模式可以方便不同数据库连接之间的移植。

  3.数据库资源管理模式

  3.1 数据库连接池技术

  资源重用,避免频繁创建,释放连接引起大大量性能开销;

  更快的系统响应速度;

  通过实现JDBC的部分资源对象接口( Connection, Statement, ResultSet ),可以使用

  Decorator设计模式分别产生三种逻辑资源对象: PooledConnection, PooledStatement和

   PooledResultSet。

  一个最简单地数据库连接池实现:

  public class ConnectionPool {

         private static Vector pools;

         private final int POOL_MAXSIZE = 25;

         /**

          * 获取数据库连接

          * 如果当前池中有可用连接,则将池中最后一个返回;若没有,则创建一个新的

  返回

          */

         public synchronized Connection getConnection() {

                Connection conn = null;

                if (pools == null) {

                       pools = new Vector();

                }

                if (pools.isEmpty()) {

                       conn = createConnection();

                } else {

                       int last_idx = pools.size() - 1;

                       conn = (Connection) pools.get(last_idx);

                       pools.remove(last_idx);

                }

                return conn;

         }

         /**

          * 将使用完毕的数据库连接放回池中

          * 若池中连接已经超过阈值,则关闭该连接;否则放回池中下次再使用

          */

         public synchronized void releaseConnection(Connection conn) {

                if (pools.size() >= POOL_MAXSIZE)

                       try {

                              conn.close();

                       } catch (SQLException e) {

                              // TODO自动生成 catch 块

                              e.printStackTrace();

                       } else

                       pools.add(conn);

         }

         public static Connection createConnection() {

                Connection conn = null;

                try {

                       Class.forName

  ("oracle.jdbc.driver.OracleDriver").newInstance();

                       String url = "jdbc:oracle:thin:@localhost:1521:orcl";

                       String user = "scott";

                       String password = "tiger";

                       conn = DriverManager.getConnection(url, user, password);

                } catch (InstantiationException e) {

                       // TODO自动生成 catch 块

                       e.printStackTrace();

                } catch (IllegalAccessException e) {

                       // TODO自动生成 catch 块

                       e.printStackTrace();

                } catch (ClassNotFoundException e) {

                       // TODO自动生成 catch 块

                       e.printStackTrace();

                } catch (SQLException e) {

                       // TODO自动生成 catch 块

                       e.printStackTrace();

                }

                return conn;

         }

  }

  注意:利用getConnection()方法得到的Connection,程序员很习惯地调用conn.close()方

  法关闭了数据库连接,那么上述的数据库连接机制便形同虚设。在调用conn.close()方法

  方法时如何调用releaseConnection()方法?这是关键。这里,我们使用Proxy模式和java

  反射机制。

  public synchronized Connection getConnection() {

                Connection conn = null;

                if (pools == null) {

                       pools = new Vector();

                }

                if (pools.isEmpty()) {

                       conn = createConnection();

                } else {

                       int last_idx = pools.size() - 1;

                       conn = (Connection) pools.get(last_idx);

                       pools.remove(last_idx);

                }

         

          ConnectionHandler handler=new ConnectionHandler(this);

                return handler.bind(con);

         }

  public class ConnectionHandler implements InvocationHandler {

       private Connection conn;

       private ConnectionPool pool;

      

       public ConnectionHandler(ConnectionPool pool){

              this.pool=pool;

       }

_                                                                                                              _

       /**

        * 将动态代理绑定到指定Connection

        * @param conn

        * @return

        */

       public Connection bind(Connection conn){

              this.conn=conn;

  Connection proxyConn=(Connection)Proxy.newProxyInstance(

  conn.getClass().getClassLoader(), conn.getClass().getInterfaces(),this);

            return proxyConn;

       }

      

         /* (非 Javadoc)

          * @see java.lang.reflect.InvocationHandler#invoke

  (java.lang.Object, java.lang.reflect.Method, java.lang.Object[])

          */

         public Object invoke(Object proxy, Method method, Object[] args)

   throws Throwable {

                // TODO自动生成方法存根

                Object obj=null;

                if("close".equals(method.getName())){

                       this.pool.releaseConnection(this.conn);

                }

                else{

                       obj=method.invoke(this.conn, args);

                }

               

                return obj;

         }

  }

        在实际项目中,并不需要你来从头开始来设计数据库连接池机制,现在成熟的开源

  项目,如C3P0,dbcp,Proxool等提供了良好的实现。一般推荐使用Apache dbcp,基本使用

  实例:

  DataSource ds = null;

     try{

       Context initCtx = new InitialContext();

       Context envCtx = (Context) initCtx.lookup("java:comp/env");

       ds = (DataSource)envCtx.lookup("jdbc/myoracle");

          if(ds!=null){

                  out.println("Connection is OK!");

                  Connection cn=ds.getConnection();

                  if(cn!=null){

                          out.println("cn is Ok!");

                  Statement stmt = cn.createStatement();

                   ResultSet rst = stmt.executeQuery("select * from BOOK");

                  out.println("<p>rst is Ok!" + rst.next());

                  while(rst.next()){

                          out.println("<P>BOOK_CODE:" + rst.getString(1));

                    }

                          cn.close();

                  }else{

                          out.println("rst Fail!");

                  }

          }

          else

                  out.println("Fail!");

             }catch(Exception ne){ out.println(ne);

           }

  3.2 Statement Pool

  普通预编译代码:

  String strSQL=?select name from items where id=??;

  PreparedStatement ps=conn.prepareStatement(strSQL);

  ps.setString(1, ?2?);

  ResultSet rs=ps.executeQuery();

  但是PreparedStatement 是与特定的Connection关联的,一旦Connection关闭,则相关的

  PreparedStatement 也会关闭。

  为了创建PreparedStatement 缓冲池,可以在invoke方法中通过sql语句判断池中还有没有

  可用实例。

  4. 持久层设计与O/R mapping 技术

  1) Hernate:适合对新产品的开发,进行封闭化的设计

  Hibernate 2003年被Jboss接管,通过把java pojo对象映射到数据库的table中,采用了

  xml/javareflection技术等。3.0提供了对存储过程和手写sql的支持,本身提供了hql语言

  。

  开发所需要的文件:

  hibernate配置文件: hibernate.cfg.xml 或 hibernate.properties

  hibernate 映射文件: a.hbm.xml

  pojo类源文件: a.java  

  导出表与表之间的关系:

  a. 从java对象到hbm文件:xdoclet

  b. 从hbm文件到java对象:hibernate extension

  c. 从数据库到hbm文件:middlegen

  d. 从hbm文件到数据库:SchemaExport

  2)Iatis :适合对遗留系统的改造和对既有数据库的复用,有很强的灵活性 3)

   Apache OJB:优势在于对标准的全面支持 4)EJB:适合集群服务器,其性能也不象某些

  人所诟病的那么差劲 5) JDO (java data object)

  设置一个Properties对象,从而获取一个JDO的PersistenceManagerFactory(相当于JDBC

  连接池中的DataSource),进而获得一个PersistenceManager对象(相当于JDBC中的

  Connection对象),之后,你可以用这个PersistenceManager对象来增加、更新、删除、

  查询对象。

  JDOQL是JDO的查询语言;它有点象SQL,但却是依照Java的语法的。

  5. 基于开源框架的Struts+Spring+Hibernate实现方案

  示例:这是一个3层架构的web 程序,通过一个Action 来调用业务代理,再通过它来回调

   DAO类。下面的流程图表示了MyUsers是如何工作的。数字表明了流程的先后顺序,从web

  层(UserAction)到中间层(UserManager),再到数据层(UserDAO),然后返回。

  Spring是AOP, UserManager和UserDAO都是接口.

  1)web层(UserAction) :调用中间层的接口方法,将UserManager作为属性注入。

   采用流行的Struts框架,虽然有很多人不屑一顾,但是这项技术在业界用的比较普遍,能

  满足基本的功能,可以减少培训学习成本。

  2)中间层(UserManager):将UserDAO作为属性注入,其实现主要是调用数据层接口的一些

  方法;它处于事务控制中。

   采用Spring框架实现,IOC与AOP是它的代名词,功能齐全,非常棒的一个架构。

  3)数据层(UserDAO):实现类继承HibernateDaoSupport类,在该类中可以调用

  getHibernateTemplate()的一些方法执行具体的数据操作。

   采用Hibernate做O/R mapping,从种种迹象可以看出,Hibernate就是EJB3.0的beta版。

                    本篇文章对您是否有帮助?  投票:是    否     投票结果:   [cool]  7     [sad]  0

  版权声明 

  作者其它文章:

   · Java调用存储过程

   · Java EE/J2EE面向对象编程之道

   · Eclipse使用技巧

   · java中的值传递

  作者全部文章

  评论人:ahliujin                               发表时间: Tue Nov 14 15:31:55

                                                 CST 2006

  收了

  评论人:jacky3621                              发表时间: Tue Nov 14 19:04:38

                                                 CST 2006

  本来觉得ConnectionPool是一个很神秘的东西,今天看了一个简单的例子,学到了不少

  的东西,使自已觉得学好J2EE更加有信心,谢谢楼主!

  [good]

  评论人:十字刀客                               发表时间: Tue Nov 14 19:14:20

                                                 CST 2006

  好的,顶。[good][:)]

  这个文章共有 3 条评论

  主题: 百度面试题(算法)   返回文章列表 返回〔J2SE综合〕  下一篇文章主题: 深入了

  上一篇文章                                              解Java 5.0的垃圾收集

  文字广告链接

         自主、快速定制基于JAVA的B/S业务系统        重量级企业在线自定义WEB报表平

  台

         数巨报表:全程图形化设计无须代码,适合J2EE、ASP及.NET等环境,功能强大的

  Web报表工具

_        Max@X Analyser5:快速建立企业级决策分析平台,释放IT系统价值的能力                                     _

         上海网域网:上海、香港、美国服务器租用服务器托管专家

  _

                        关于 JR  |  版权声明  |  联系我们

                     (C)2002-2006 JR 版权所有沪ICP备05019622号

孩子终于又生病了

说实话,我对孩子现在的健康状态还是比较满意的,平时她喝冷水,玩水,吃不少东西,都没事。可以说是身体健康程度越来越好。但是,从前天晚上开始,孩子又生病了。这算是好几个月来的又一次生病吧。

前天晚上,孩子半夜醒来,脸通红,嚷着要喝水,还说她做了恶梦。我们安慰了她一下。就没有当一回事。

昨天中午后,我去上班了。孩子突然发起烧来,到医院查了一下,有39度了。儿科医生看了,说是扁桃体发炎,并且已经化脓了。建议输液。我们觉得不要一开始就用这种方法。老师就开了三天的针药和一些吃药。从昨天下午起,孩子就没有去上幼儿园了。

今天早上,孩子嚷着要喝冷水,给她换成热水,不依,又是一阵哭闹,最后还是喝的冷水。早上起来,她要像往常一样吃鸡蛋,因为听说发烧不能吃蛋,不准备给她吃,又闹,只好又依了她。

我想,只要她想吃,如果没有大问题,就让她吃吧。只要吃得进去,有能量抵抗疾病,这才是根本吧。

昨天,孩子可能因为扁桃体发炎,喉咙疼,没有怎么吃饭。今天能吃东西,应该是好事吧。

先把医生开的吃药和针药用完,如果没有什么好转的话,再考虑医生建议的输液吧。

Thinking in Patterns chapter 5: Object decoupling

Thinking in Patterns with Java V0.9: chapter 5: Object decoupling: TIPatterns.htm#_Toc41169699

1, The sections name of today's learning;

    Proxy: fronting for another object 31

        The PoolManager using Proxy. 33

        Dynamic Proxies. 36

    State: changing object behavior  38

    Iterators: decoupling algorithms from containers  44

        Type-safe iterators. 45

    Exercises. 46

 

2, What is it talk about in these sections and my comments and feeling for the content;

  At the begin of this chapter, Bruce put up with his own opinion about

pattern Proxy and State. In his mind, these two patterns are simlar

structurely while GoF's these two patterns are different structurely. They are

all the surrogate "controlling access to implementation". Only Proxy access a

fixed implementation while State access several implementations dynamically.

From his opinion, he point some "mistake" written in GoF's Design Patterns,

you can see these words at the end of State patterns, like this:" Rewrite this:

In Design Patterns, Proxy and State are not seen as related to each other because the two are given (what I consider arbitrarily) different structures." ,and so on.

  I haven't read GoF's Design Patterns, so can't write some my feeling. I only

want to say, speaking with own mind, Bruce, a real master.

  Bruce says: The basic idea is simple: from a base class, the surrogate is derived along with the class or classes that provide the actual implementation:(I think his meaning is the same idea is used for proxy and state pattern)

  1), Proxy: fronting for another object

  I think proxy patterns can decouple objects, the reason is add a middle layer between the client and implementation class. When the implementation class change, the interface class that is proxy which will don't change. From my poor experience, I haven't tasted it's power. From my mind, why does add another layer between them? The changes is always happened on implementation class regardless the existence of proxy class. I think I should read more famous open source project like jive or pet store application.

  Although I understand the basis concept of proxy pattern, and I can see some code of example The PoolManager using Proxy, but spending some minutes on it, I can't understand this complex example yet, I can only put it there, maybe after this overview of book, I can see it entirely when I revisit this example.

  I can't compile the example Dynamic Proxies, and can't under this this section, and, I can't know why Bruce add a comment "// Broken in JDK 1.4.1_01" in the class file "proxy:DynamicProxyDemo.java" that showed in html page but isn't included into code folder of this electronic book. I think maybe I need learn the java.lang.reflect.Proxy class in the JDK.

 

  2), State: changing object behavior

  At last, I understand why this pattern be included into the category "object decoupling". For performing different action according to the certain condition, if no state object involved, it will be added some testing code in some methods.

  State pattern is implemented with the power of "polymorphism", from my understanding, State pattern is just one object hold a state object as a state property, according to the state object's change, that object will change its action. 

  3), Iterators: decoupling algorithms from containers

  In this section, an interesting term named "functional programming" give me strong impression. Walk along with this direction, maybe the programer's work will change huge, because it says: functional programming, whose objective is to describe what a program is doing at every step rather than how it is doing it. That is, you say “sort” rather than describing the sort. In a expand notion: if you want to get an application, you just need only say to computer, do a program that should own the functions below: 1,...; 2, ...;

  Because the templete techniqe has raised in JDK5 (but I have never used this new feature:( ), maybe Bruce need rewrite his Type-safe iterators example.

 

3, My questions about the program itself;

  Too many, include: example PoolManager using Proxy, section Dynamic Proxies, and inner class, the "static" keyword in the inner class, all exercises, etc....

4, My questions about the english language;

  1), Strange words:

  surrogate, notion, tempt, lump, long-standing, front for, speak for, at odds, orthogonal, tale, princess, awkward, aliasing, arbitrarily, specifics, through to, backend, backend Builder object, algorithms, algebraic, STL, candidates, problematic, iteration, establish, Decorator, Unpredictable, mood, copy-on-write, leasing

  2), Strange sentences;

    1>, as long as Proxy is somehow “speaking for” the class that it is referring method calls to then the basic idea is satisfied (note that this statement is at odds with the definition for Proxy in GoF).

    2>, how successful this approach will actually be remains to be seen.

**********************************************************************************************

//: state:StateDemo.java

// Simple demonstration of the State pattern.

 

                                          incomplete

Thinking in Patterns chapter 4: Object quantity

Thinking in Patterns with Java V0.9: chapter 4: Object quantity: TIPatterns.htm#_Toc41169694

1, The sections name of today's learning;

Singleton. 25

  Exercises. 27

Object pool 27

  Exercises

 

2, What is it talk about in these sections and my comments and feeling for the content;

   1), Singleton just like youself, only one, can't be duplicated, this can be used in a stiuation that only one object of this class can be created.

   Bruce speaks a lot about avoiding the singleton object to be duplicated by a new() method or clone() method. He puts up with these ways:

   1>, "make all constructors private, and you must create at least one constructor";

   2>, preventing to be cloned: 

   "making the class final prevents cloning";

   "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 of Thinking in Java, 2nd edition."

   2), Object pool is only limited quantity object can be created. The quantity of objects in pool will reduce one if use one, the object pool will empty if all the objects are used, unless someone return to unused state.

   A question: if the objects in pool will be destroyed in a fixed period regardless of their states is used or unused, how can I use the object at anytime? Some virtual host provider will clear database connections in this way. My anwser is: Before getting connection from pool, check if there are some objects in the pool, if no any object in pool, then call pool manager to create these limited quantity objects again. 

3, My questions about the program itself;

   1), How JVM works when create a object with class's private constructor?

   2), How to use method clone()?

   3), Static inner class

   4), a class can be singleton by make all the method static

   5), Every chapter's exercises will not to be done this time's reading. 

4, My questions about the english language;

  1), Strange words:

  synthesizing

                                           incomplete

Thinking in Patterns chapter 3: Simplifying Idioms

Thinking in Patterns with Java V0.9: chapter 3: Simplifying Idioms: TIPatterns.htm#_Toc41169691

1, Sections name of today's learning;

    Messenger. 22

    Collecting Parameter. 24

2, What is it talk about in these sections and my comments and feeling for the content:

  Bruce's book always give me good reading experiment.

  He puts the Messenger and Collecting parameter at Simplifying Idioms

chapter, I think the reason is that these two patterns can be used in the basis implementation of a process which performing a specific task.

  1), Messenger.

  If we need translate many related parameters into a method, we can package

these parameters into an object, then we can translate this object into that method instead.

  I think I can use this Messenger pattern in our LearnDiary Open Source

Project like this: Because we use Struts framework, it need tranlate some

attributes from a Struts Action into a Jsp page, my method before is set these

attributes into request scope seperately, then get these attributes in Jsp

page seperately; Now, if some of these attributes is related, we can package some of these attributes into an attribute object, then translate this packaged attribute object into Jsp page. But, I think this need balance, we can't package all the attributes into only an attribute object without any proper reason.

  2), Collecting Parameter.

  Frankly speaking, I have never used Collecting Parameter patterns before, I

haven't ever thought that a parameter can be used like this: pass a parameter

into a method, let this method do some change on this parameter, then pass

this changed parameter into another method, and let this another method do

some change on this changed parameter again, and so on. That's really an

intresting use of a parameter. Just like flow line production:). But,

remember, the parameter is always only one same object, only the content of

this object changed. 

  Let me think a while, how can I use this pattern into our LearnDiary

project? aha, a little example coming, in our project, there is an Email

object, it consists of email address and title, content, and so on. Email

address can be gotten from user object, and email's title and content can be

gotten from an article object. So, create method at user and article object

for adding some field into email object. Then, translate email object into

user and article object's corresponding method to do some change in turn.  

 

3, My questions about the english language;

  1), Strange words:

  trivial, pass around, magnitude, dummy, pollen, accumulating

孩子急躁时怎么办?

  我们的孩子性情比较急躁,这从她很小的时候就可以看出来。只要她急起来的时候,很难听进去大人一般的对话。非要达到她自己的意愿为止。对于她这种急躁的性格,我也在日记里记录过几次,见:咪妹是个横牛(1岁多的时候),对孩子的任性也宽容点吧?,实际上,像这样的情况多了,只不过没有一一的记下来而已。

  昨天,又碰到一个事情。孩子看到别的小孩穿在脚上的旱冰鞋,就跑回来非要要。我们向她解释说,那是大点的孩子玩的,你这么小,没有合适的旱冰鞋。可她就不听,非要不可,一直哭闹。真是无可奈何。

  这时,我觉得我的处理方式还算行。我自己蹲下来,仍然轻言细语的对她说:“这样吧,你跟外婆到商场里去看看,我们看到合适的就给你买,好不?”她好像也知道商场里不会有是的,就是不去商场,而且还非要要。

  于是,我又轻轻的对她说了一些类似的话,渐渐的,孩子同意到商场里去看看,也就不哭了。

  所以,我的意见是:孩子急躁时,大人不能跟着急躁,不然是没有办法解决问题的。只有用点缓兵之计,先顺着她的意思说,在她的情绪稍微稳定了,再给她讲理,也许她就会听了。

  这个方法初见成效,以后碰到类似的事情再继续检验这种处理方式是否真的好用。

隐藏网页中的文字和使用锚点

这是在看准备用英文版的Thinking in Patterns学习设计模式时的一点意外收获:)

我发现在文本浏览器w3m中看这本书的目录时里面有数字,而在图形界面的浏览器中看则没有(详见:Outline of Thinking in Patterns with Java)。于是,我查看了网页的源码,发现原来使用了隐藏文字的技术(这个技术是什么名字我也叫不上,反正是这个效果)。从其中我知道隐藏文字可以用:


          <span style='color:windowtext;display:none;text-decoration:none'>

            .

          </span>

链接到锚点可以这样:


<a href="#_Toc41169680">

...

</a>

全部实验代码如下:

1)、隐藏文字:


<html>

  <head>

    <title>

      Test hiding some text in page

    </title>

  </head>

  <body>

    <p class=MsoToc2>

      <span class=MsoHyperlink>

        <a href="#_Toc41169680">

          The Y2K syndrome

          <span style='color:windowtext;display:none;text-decoration:none'>

            .

          </span>

          <span style='color:windowtext;display:none;text-decoration:none'>

            11

          </span>

        </a>

      </span>

    </p>

  </body>

</html>

2)、显示文字:


<html>

  <head>

    <title>

      Test displaying some text in page

    </title>

  </head>

  <body>

    <p class=MsoToc2>

      <span class=MsoHyperlink>

        <a href="#_Toc41169680">

          The Y2K syndrome

          <span style='color:windowtext;text-decoration:none'>

            .

          </span>

          <span style='color:windowtext;text-decoration:none'>

            11

          </span>

        </a>

      </span>

    </p>

  </body>

</html>

附网上摘的一段使用锚点的段落:(摘自:http://www.sdau.edu.cn/support/html/html_cn.htm


连结 <A HREF="URL"></A>

连结到锚点

<A HREF="URL#***"></A>(如果锚点在另一个档案)

<A HREF="#***"></A>  (如果锚点目前的档案)

N2.0 连结到目的视框 <A HREF="URL" TARGET="***"></A>

设定锚点 <A NAME="***"></A>

Thinking in Patterns Chapter 1: introduction

Thinking in Patterns with Java V0.9:  Chapter 1: introduction: TIPatterns.htm#_Toc41169679

1, The sections name of today's learning;

    The Y2K syndrome. 11

    Context and composition. 12

    A word about checked exceptions  13 

2, What is it talk about in these sections?

   Even my english is poor, but in order to learn it, I will write some my viewpoints of the content. After finishing read this book once, and to see a chinese version of this book, maybe I will rewrite some words at here.

   First, I am amused the term GoF is conerned with that well-known four persons in China include JiangQing, WangHongWen, etc..

  The first part tells us, you must have learned some basic OOP and have used Java some time, then you can read this book, it isn't for a beginer of Java or program.

  In section The Y2K syndrome, it tells us, focus on the key that is really the bottleneck of system, usually, only 10% code is this key, don't perform some optimization according to your own thinking without deeply testing. I think Bruce put these words at this location of this book, the meaning maybe is Design Patterns can be used at the key part of system(only 10%), for non-key part, you don't think the Design Patterns should be used everywhere.

  Bruce introduces two terms which is Context and composition, maybe he thought these two terms is very important in the Design Patterns? Because I haven't read some basic knowledge about Design Patterns, so I can't understand these two terms well. But I should remeber these words: "The context object allows you to use the pattern in a composition, and that may be it’s primary value.". Maybe I can understand these after reading this book.

  In fact, I don't think Bruce should put the content about "checked exceptions" at here, to Design Patterns, how important the "checked exceptins" is? In these part, I know Bruce discontented the "checked exceptions" in C++ and Java except Python. This part I can't understand it well, but I can get one is: "I intend to put a lot more RuntimeExceptions into my Java code".

  

3, My comments and feeling for the content?

  no.

4, My questions about the program itself;

  1), What on earth is Context object in the Design Patterns ?

5, My questions about the english language;

  1), Strange words:

  evolve, rudimentary, syndrome, subtitle, pitfall, terms, as far as, predicting doom, as if, premature, virtually, happen, particular, facade, knowledge, silly, past, dominate, landscape, turn around, intrude, go up, vanish, ream, opposite, tongue-in-cheek, widow, demonize, chronicle

  2), Strange sentences:

  Y2K syndrome:

  1>, Also,everyone seems to reserve in their own mind a special case ?except for this thing that I happen to know is a particular problem.?

  2>, these things aren?t so difficult after all, if I can see such an obvious problem.

  3>,  As a result, I know that many

embedded systems have no idea what the date or time is, and even if they do

that data often isn?t used in any important calculations. And yet I was told in

no uncertain terms that all the embedded systems were going to crash on January

1, 2000. As far as I can tell the only memory that was lost on that particular

date was that of the people who were predicting doom ? it?s as if they had

never said any of that stuff.

  4>, ?We should forget about small efficiencies, say about 97% of the time:

Premature optimization is the root of all evil.??Donald Knuth

  5>, My experience with Python exceptions supports this, and unless I get turned around on this issue I intend to put a lot more RuntimeExceptions into my Java code.

                                           incomplete