Thinking in Patterns Chapter 11: Flexible structure

Thinking in Patterns with Java V0.9: Chapter 11: Flexible structure: TIPatterns.htm#_Toc41169735

1, Sections:

  Composite

2, The main content and feeling:

  At first, the meaning of "Composite" has confused me a little. There is a

"Composition" and "Aggregation" terms in UML. And, I thought "Composite" in

GoF's design patterns as the "Composition" in UML. At last, I have known these

two terms are all totally different.

Here, I don't give the explaination of "Composition" term in UML, you can get

it at our site:

http://java.learndiary.com/disDiaryContentAction.do?goalID=1345

I understood the meaning of "Compostion" after reading the example://:

composite:CompositeStructure.java. The key is: The node and its child node has

the same operations, "and that performing an operation on a node/composite

also performs that operation on any children of that node/composite."

Just like an orgernization, there are some partions under this orgernization,

and alse maybe there are lower partions under the orgernization's partion.

When the leader of orgernization say: do(it), the entire orgernization start a

mission just "do(it)". Then, every partions of

orgernization and the lower partions of the orgernization's partion will also

perform this "do(it)" mission. But, the detail of "do(it)" in all these level

isn't same.

And, there is a point about "passing parameter to a java method" need be

noted.

See the code part below:


    Node c2 = new Node("Node1"); //Step 1

    //some code omited

    root.add(c2); //Step 2

    c2 = new Node("Node2"); //Step 3

    //some code omited

 

   root.add(c2); //Step 4

At Step 2, a duplicated copy of the address of object created at Step 1 passed

into method add(); and, the reference "c2" point to a new object, again,

another object's address be duplicated into the method add() at Step 4. Note,

the object pointed by "c2" at Step 2 will can't be changed by a new object to be

pointed by "c2".  

If you are confused with the "passing parameter into a java method" like

above, maybe, an article of mine titled with "Understanding Assignment and

Passing Parameters in Java with Term 'Stack Date Copy'" posted at:

http://java.learndiary.com/disDiaryContentAction.do?goalID=2716 can help you to understand it.

3, Questions about programming:

4, Questions about english language:

1), Strange words:

part-whole, containment, visitation,

2), Difficult sentences:

1>, The important thing here is that all elements in the part-whole have

operations, and that performing an operation on a node/composite also performs

that operation on any children of that node/composite.

                                     incomplete

Thinking in Patterns chapter 10: Connecting different types

Thinking in Patterns with Java V0.9: chapter 10: Connecting different types: TIPatterns.htm#_Toc41169731

1, The sections name of today's learning;

Adapter. 84

Bridge. 87

Exercises. 93

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

Maybe, I have gotten most feeling in this chapter. After some reading and thinking, I think I have understood these two patterns. In addition, through this chapter, I have known a little more about Proxy pattern.

1), Adapter

From my feeling, Adapter can be seen as a generlization of Proxy, and Proxy is a specific of Adapter. My understanding is below:(UML diagram is at the end of this diary)

1>, From the example: adapter:SimpleAdapter.java for Adapter and the example: proxy:ProxyDemo.java for Proxy, we can see little difference between them;

2>, From the example: adapter:AdapterVariations.java for Adapter, I haven't seen a little piece of Proxy.

Then, let us see their effects:

Proxy: fronting for another object

Adapter: Connecting different types

So, I can say in Proxy pattern: the proxy object and the implementation object these two types objects are connected by the Proxy pattern;

And, Adapter has more usage, it can unite different objects to achieve a job.

Review Bruce's words about proxy(in the end of section: Proxy: fronting for another object in chapter: Object decoupling): Of course, it isn’t necessary that Implementation have the same interface as Proxy; 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).

Then look at this statement at the end of this section: I’m taking liberties with the term “proxy” here, because in Design Patterns they assert that a proxy must have an identical interface with the object that it is a surrogate for. 

Maybe, I have found the reason of GoF's "assert that a proxy must have an identical interface with the object that it is a surrogate for. ", only in this way, Proxy pattern can be a standalone pattern in 23 patterns, otherwise, maybe it can be mixed into adaper, then, there are only 22 patterns exist now:)

And, maybe, Proxy has been used long time by people, we can't ignore its existence, it must be a standalone pattern. And, its work focuses on "fronting for other".

I can't express my entire feeling with my poor english, maybe, writing my diary in english is an error?

2), Bridge:

The most feeling in this chapter is: don't think that authority's words is all right, including GoF's. Bruce got a result after listening some other's idea about Bridge pattern, this result is: GoF's Design Patterns did "a miserable job of describing Bridge", and, there is only one place in GoF's Design Patterns is a lightspot-Bruce says continuely:"except in one place not the general structure chart describing the pattern, which wasn't helpful, but in the structure chart describing their specific example. Only if you stare at that for a bit does Bridge begin to make sense.". From this only lightspot, Bruce put up with a example of his Bridge pattern (and, maybe, is also GoF's), and, at least, I know the Bridge pattern is "often a construct that is used to help you write code. ", and it's goal is "to allow you to structure your code so that you can easily add new kinds of front-end objects which are implemented with functionality in new kinds of back-end objects."

An another meaningful statement for me is "But keep in mind that the vector of change with Bridge is typically happening at coding time: it keeps your code organized when you are dealing with an increasing number of options for implementing functionality."

Bridge pattern is a bridge between "front-end objects" and "back-end objects", regardless the number and the type of all these objects, it can provide an interface at front-end, receive all other front-end objects' requests and hand these requests to back-end interface, and it provides an interface at back-end, receive the requests which come from the front-end interface and hand these requests to back-end objects to fulfill the requests.  

3, My questions about the program itself;

1), the real application of these two patterns;

2), exercises;

4, My questions about the english language;

1), Strange words:

adaptee, take liberty with, unenlightened, begin by, conference, perspectives, give (a) talk, armed with, misinformation, delve, miserable, construct, in common, delegate, combinatorial, bookkeeping, clerking, associative, radically, Effectively

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

//: proxy:ProxyDemo.java

// Simple demonstration of the Proxy pattern.

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

//: adapter:SimpleAdapter.java

// "Object Adapter" from GoF diagram

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

//: adapter:AdapterVariations.java

// Variations on the Adapter pattern.

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

//: bridge:BridgeStructure.java

// A demonstration of the structure and operation

// of the Bridge Pattern.

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

demonstrate the structure of Bridge

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

                          incomplete

Thinking in Patterns chapter 9: too many

Thinking in Patterns with Java V0.9: chapter 9: too many: TIPatterns.htm#_Toc41169721

1, The sections name of today's learning;

  Flyweight: too many objects. 66

  Decorator: too many classes. 69

    Basic decorator structure. 70

    A coffee example. 70

    Class for each combination. 70

    The decorator approach. 73

    Compromise. 78

    Other considerations. 82

    Exercises. 83

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

  I have never felt the design pattern's importance so strong until I read this chapter, especially the section Decorator: too many chasses.

  1), Flyweight: too many objects. 66

  For my understanding, the key of Flyweight pattern is: put all the objects of a class into one object which I named it "all_in_one", get the any object of many object from this "all_in_one" object by passing the "index" of any object of many object into this "all_in_one".

  By running the modified example in this section, I am sure it's really true.

  I modified "size = 1000000" to "size = 5000000" in flyweight:ManyObjects.java, and ran it, it reported:


Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

        at ManyObjects.main(ManyObjects.java:22)

The same "size = 5000000" in flyweight:FlyWeightObjects.java works well, and the running time is less much than the running time in flyweight:ManyObjects.java with "size = 1000000"( with a less size, it works.).

At the end of this section, Bruce warn us don't do a "premature optimization" by using flyweight pattern unless discovering performance bottlenecks of too many objects by using a profiler tool, I think if I haven't misunderstood his words.

2), Decorator: too many classes. 69

Just this pattern give me so strong of pattern's importance. And, the example of "coffee shop" posted by Bruce is so natural and proper. I can understand the meaning of this pattern by this example even the program detail isn't very clear for me.

For my understand, I put up another example for this pattern: "man", then decorate "man" with "good man", "wise man", "old man", "strong man", at last, a strong old wise good man appears.

Without the Decorator pattern, there will be many class need to be created in Bruce's coffee shop example.

With the Decorator pattern, there are two approachs, one is "pure" decorator, and another is compromise which mixes the approach of without decorator and with decorator.

In most real stiuations, a compromise way should be taken.

This is really a book which "Problem-Solving Techniques using Java".

The uml classes diagrams of these three approachs of solving too many classes problem which from this book is at the end of this diary.

3, My questions about the program itself;

1), "implicit this pointer in method calls, the “this index” is passed in as the first argument.", how does the implicit "this" pointer work step by step in JVM? 

4, My questions about the english language;

1), Strange words:

flyweight, odd, in the company of, hack, prohibitive, excessive, externalize, pretend, untenable, admonishment, guesswork, layered, refer to as, account for, go down to, espresso, latte, teas, whip, decaf, sizeable, Mocha, steamed, foam, conform to, mug, assembling, arduous, Compromise, present, get away, syrup, Follow the compromise approach to create a menu consisting of a Margherita, Hawaiian, Regina, and Vegetarian pizzas, with toppings (decorators) of Garlic, Olives, Spinach, Avocado, Feta and Pepperdews. Create a Hawaiian pizza, as well as a Margherita decorated with Spinach, Feta, Pepperdews and Olives. detaching, beverage

2), Strange sentences:

1>, Firstly, the combinations are fixed statically so that any combination a customer may wish to order needs to be created up front.

2>, However, the implications to the all decorator or compromise approaches are the same - one extra class is created.

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

Basic decorator structure

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

Class for each combination

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

The decorator approach

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

Compromise

Thinking in Patterns chapter 8: Specialized creation

Thinking in Patterns with Java V0.9: chapter 8: Specialized creation: TIPatterns.htm#_Toc41169717

1, The sections name of today's learning;

Prototype. 61

Builder. 62

Exercises. 66

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

1), Prototype

Come up with it at this chapter, but will descript it later.

2), Builder.

"They never define exactly what they mean by representation. ", "but alas, ", etc... Again, Bruce appears to be not satisfied with the GoF's work about this part. At the end of this section, Bruce gives a simple definition of "Builder" pattern is: "Thus, Builder could be described as using a Policy to create objects."

And, maybe I have known a difference between "State" and "Builder" is: State "simply forwarding the requests" , Builder "has a sequence of operations to perform", and both "State" and "Builder" is called by a context to perform its job. At this point, maybe I have seen a little meaning of the "context" which mentioned at the begin of this book as "it will often be the controller that manages the operation of the pattern". In the example: state:StateDemo.java, the context class is "ServiceProvider", in the example: builder:BuildMedia.java, the context is "MediaDirector".

And, maybe I have also known a little of statement appeared at the section of State pattern: "State can be found everywhere because it’s such a fundamental idea. For example, in Builder, the “Director” uses a backend Builder object to produce different behaviors.".

At this point, the difference of "State", "Strategy", "Policy", "Builder" patterns make me a bit dizzy. But, I think if I read more source code of these patterns and apply these patterns in some real projects (like LearnDiary), maybe I will master these patterns really, and maybe create my own design patterns, isn't it?

3, My questions about the program;

1), Although the resulting “object” (the entire converted text file) is created over time, if you consider the conversion of each RTF directive to be an object, this feels to me a little more like Bridge, because the specific types of converters extend the interface of the base class.

2), exercises;

4, My questions about the english language;

1), Strange words:

representation, spread out, over time, essence, maze, alas, overwhelmingly, compelling, a.k.a. (Also known as.), in some ways

2), Strange sentences:

1>, The final variation of the maze builder is something that doesn’t create mazes at all, but instead counts the rooms in an existing maze.

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

UML classes diagrams of examples mentioned in this chapter:

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

//: state:StateDemo.java

// Simple demonstration of the State pattern.

 

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

//: strategy:StrategyPattern.java

//Strategy: choosing the algorithm at run-time

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

//: builder:BuildMedia.java

// Example of the Builder pattern

                                                      incomplete

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号

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