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

Java参数传递方式(转帖)

转自:http://www.jiehoo.com/java-pass-parameter.htm

Java参数传递方式

其实这个问题我原来翻译(破除java神话之二:参数是传址的 )、转帖别人的详细解释(Java 应用程序中的按值传递语义 )和专门解释( 我对《Java 应用程序中的按值传递语义》的理解)过,不过现在看来,原来翻译或者解释的角度是有问题的,从底层的角度解释并不直观,在交流的时候也容易引起误解,最终不能达成一致意见。下面以最终的效果来解释参数的传递方式:

1、对于原始数据类型,也就是int、 long、char之类的类型,是传值的,如果你在方法中修改了值,方法调用结束后,那个变量的值没用改变。

2、对于对象类型,也就是Object的子类,如果你在方法中修改了它的成员的值,那个修改是生效的,方法调用结束后,它的成员是新的值,但是如果你把它指向一个其它的对象,方法调用结束后,原来对它的引用并没用指向新的对象。

代码如下:

public class Tester {

    public static void main(String[] args) {

        int primitive = 2;

        changePrimitive(primitive);

        //primitive的值依然是2

        MyClass myClass = new MyClass();

        changeObject(myClass);

        //myClass仍然指向的是执行changeObject之前的那个对象

        //但是myClass.i等于3了

    }

    public static void changePrimitive(int primitive) {

        primitive = 3;

    }

    public static void changeObject(MyClass myClass) {

        myClass.i = 3;

        myClass = new MyClass();

    }

}

class MyClass {

    int i;

}

对于远程调用,无论是什么类型,调用结束后,传入的参数和以前没用任何变化(当然前途是直接调用远程方法,如果中间经过其它的Proxy类或者Facade类,不能保证那些类对对象没用修改)。至于是通过Locale接口进行调用的,我不太清楚是否属于远程调用。以后确定了再来更新。

作者: Cherami

原载: Java参数传递方式

版权所有。转载时必须以链接形式注明作者和原始出处及本声明。

相关日志

    * 修复不能评论的问题

    * 使用参数方式还是页面配置方式

    * 我使用的WordPress插件

    * 解析XML的时候完全忽略DTD

随机日志

    * 机场也可以种树

    * Response被关闭

    * Java面试中的经典对比问题

    * 在目录中查找类位于哪个jar包中

添加到网摘

[del.icio.us]  [新浪 VIVI]  [365key]  [YouNote]  [博采中心]  [Poco]  [SOHU狐摘]  [天极网摘]  [和讯网摘]

喜欢这个插件?

当前日志信息

标题:

    Java参数传递方式

发表:

    2006-11-15

分类:

    Java

标签:

    java, 参数传递, 传值, 传引用

点击:

    28

评价:

    Votes | Average: 0 out of 5 Votes | Average: 0 out of 5 Votes | Average: 0 out of 5 Votes | Average: 0 out of 5 Votes | Average: 0 out of 5 (暂无评价)

    Loading ... Loading ...

该日志共有 3 条评论

发表评论 | RSS订阅 | 反向链接

   1. oneal 2006-11-15

      local 调用相当于同一个虚拟机上的对普通对象方法的调用。

      上面那段代码眼熟啊,上个月做过,哈哈。

   2. Cherami 2006-11-16

      local调用可能是本地调用,但是感觉有可能会换成远程调用,这样如果没有意识到,可能会有潜在的bug。因为本地调用和远程调用的特性是不一样的。可能会误用特性。

   3. English Study and Sharing » 博客文章 » Java参数传递方式 2006-11-19

      […] 对于远程调用,无论是什么类型,调用结束后,传入的参数和以前没用任何变化(当然前途是直接调用远程方法,如果中间经过其它的Proxy类或者 Facade类,不能保证那些类对对象没用修改)。至于是通过Locale接口进行调用的,我不太清楚是否属于远程调用。以后确定了再来更新。 作者: Cherami 原载: Java参数传递方式 […]

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

不能对孩子开这样的玩笑!

昨天中午,我送孩子上幼儿园。到了幼儿园门口,她非要零食吃。孩子这段时间吃零食太多了。在家里才吃了零食,所以我不准备给她买。店主在里面,我没有自己喊。孩子自己喊了几声没反应。我就开玩笑地对她说:“你看,老板不在,买不成。你想吃,自己去拿吧,看拿不拿得到?”

她站在玻璃柜台前面,往里看了又看,看玻璃柜后面。很像跃跃欲试的感觉。我一看,马上意识到我已经无意中犯了一个错误,也许还不小。就自己喊了老板给孩子买了零食吃。

这样的玩笑不能够对孩子开。孩子就像一张白纸,是没有任何对错是非观念的。你叫她去柜台里直接拿吃的,也许在她的理解就是:大人都叫我拿,这肯定是可以拿的了。如果经常反复这样,对孩子的行为习惯的塑造极为不利。

我记得自己读小学1,2年级的时候,自己还算老实吧,跟一个很调皮的孩子一起玩。然后就很自然的一起从一个缝隙钻到大伯屋里偷偷拿了大伯的钓鱼杆,这事还引起了大人之间的误会。在我当时的印象中,根本就不知道这叫作“偷窃”。

所以,我想起,有些大人爱跟小孩子开玩笑,比如,叫孩子去拿别人的东西,去打别人,去骂别人(如不雅的外号),等等。结果,在大人的哈哈大笑中,可能就给小孩的行为习惯甚至道德的培养上留下了阴影。

所以,在孩子面前开玩笑,大人们还需要三思而后行!

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号

孩子终于又生病了

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

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

昨天中午后,我去上班了。孩子突然发起烧来,到医院查了一下,有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