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

Outline of Thinking in Patterns with Java

Today, I found it can't sperate chapters in w3m brower in text mode of Linux. So, copy the Contents section at here, and seperate chapters by indenting the character. It hasn't indented After the line consist of "*".

Contents

Preface  8

Introduction  11

    The Y2K syndrome. 11

    Context and composition. 12

    A word about checked exceptions  13

The pattern concept 15

    What is a pattern?. 15

    Pattern taxonomy. 17

    Design principles. 18

    Classifying patterns. 19

    The development challenge. 21

    Unit testing. 21

        Location of test code. 22

Simplifying Idioms  22

    Messenger. 22

    Collecting Parameter. 24

Object quantity  25

    Singleton. 25

        Exercises. 27

    Object pool 27

        Exercises. 30

Object decoupling  30

    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

Factoring commonality  47

    Strategy: choosing the algorithm at run-time  48

    Policy: generalized strategy. 50

    Template method. 50

        Exercises. 52

Encapsulating creation  52

  Simple Factory method. 53

  Polymorphic factories. 55

  Abstract factories. 58

  Exercises. 61

Specialized creation  61

  Prototype. 61

  Builder. 62

  Exercises. 66

Too many  66

  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

Connecting different types  84

  Adapter. 84

  Bridge. 87

  Exercises. 93

Flexible structure  93

  Composite. 93

System decoupling  95

  Observer. 95

    Observing flowers. 97

    A visual example of observers. 101

  Mediator. 103

  Exercises. 104

Reducing interface complexity  104

  Façade. 105

    Package as a variation of Façade  106

Algorithmic partitioning  106

  Command: choosing the operation at run-time  106

    Exercises. 109

  Chain of responsibility. 109

    Exercises. 112

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

Externalizing object state  113

Memento. 113

Complex interactions  114

Multiple dispatching. 114

Visitor, a type of multiple dispatching  117

Exercises. 119

Multiple languages  120

Interpreter motivation. 121

Python overview.. 122

Built-in containers. 123

Functions. 124

Strings. 125

Classes. 127

Creating a language. 130

Controlling the interpreter. 134

Putting data in. 134

Getting data out. 140

Multiple interpreters. 143

Controlling Java from Jython  144

Inner Classes. 148

Using Java libraries. 148

Inheriting from Java library classes  150

Creating Java classes with Jython  151

Building the Java classes from the Python code  156

The Java-Python Extension (JPE)  157

Summary. 157

Exercises. 158

Complex system states  159

StateMachine. 159

Exercises. 169

Table-Driven State Machine. 169

The State class. 171

Conditions for transition. 172

Transition actions. 172

The table. 172

The basic machine. 173

Simple vending machine. 174

Testing the machine. 179

Tools. 180

Table-driven code: configuration flexibility  180

Table-driven code using anonymous inner classes  180

Exercises. 180

Pattern refactoring  181

Simulating the trash recycler. 182

Improving the design. 186

“Make more objects”. 186

A pattern for prototyping creation  189

Trash subclasses. 193

Parsing Trash from an external file  195

Recycling with prototyping. 198

Abstracting usage. 199

Multiple dispatching. 203

Implementing the double dispatch   204

The Visitor pattern. 211

A Reflective Decorator. 214

More coupling?. 219

RTTI considered harmful?. 220

Summary. 223

Exercises. 224

Projects  225

Rats & Mazes. 225

Other maze resources. 230

XML Decorator. 230

A: Tools  230

Ant extensions. 231

Array utilities. 232

Download this book at: http://www.mindviewinc.com/downloads/TIPatterns-0.9.zip

个人网站,不要流量也一样赚钱!(转帖)

转自:http://www.cn-pn.com/article/1/60.html

网站需要策略和运作,任何网站都是。下面这篇文章可以作为大家做任何网站的一点参考。

正文:

××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

个人网站,不要流量也一样赚钱!

编辑:flymorn 来源:eczn.com 更新:2006-10-31 20:58:36 点击:

【字体:小 大】

摘要:个人网站,不要流量也一样赚钱!个人站长最擅长拉流量的方式就不外乎QQ广告群发。论坛发贴,砸钱,这些都手段却是能起到一定的作用,但是需要投入大量的人力和财力。

关键字:网站 流量 网赚

正文:

在写这个标题的时候。很多人点击进来看是觉得很好奇。个人站没流量拿什么赚钱,这似乎不可能,现在我来告诉你,这是完全可以的。很多站长认为。网站要赚钱,先从流量开始。其实这是一个误区,作网站要赚钱不是先从流量开始。而是先从品牌开始。

个人站长最擅长拉流量的方式就不外乎QQ广告群发。论坛发贴,砸钱,这些都手段却是能起到一定的作用,但是需要投入大量的人力和财力。

最近在DONEWS.“庞”出现的频率甚多,而其自创的BLOG招聘也打出中国第一。每每公司有新人进来之时也要在BLOG上大赞,而最吸引人的眼球是 “加入我们,3年,您有望成为千万富翁 ”,使得庞的QQ人满为患,“世外桃源,高薪水,高待遇,老板的传奇经历”,无不吸引着每个人的眼球。庞是个极其敏锐,极富洞悉力的新新人类,而他的得力干将屠则是擅长网络营销的高手,加之其在BLOG里自暴喜欢研究周易。而在中国很少有听说搞IT的还擅长周易相学。

细心的人可以发现,这是一种品牌营销的战略,2004年火了的刀郎,庞龙,在不闻其人先闻其声的策略下,歌曲在网络上迅速窜红,他们卖的是关子,不论是批评还是赞扬,他们却是火了一把,顺便那个假“刀朗”称火打劫一把,也来凑个热闹。这些迅速走红的歌手从一开始的闻其声不见其人,到最后的频繁在媒体露面,接受采访,办演唱会,张扬,绯闻,炒作,与之前的低调作风格格不入,可见其营销策略。

大家经常说,无论是黑猫白猫,只要能抓耗子就是好猫,谁都想兜里的钞票揣得鼓鼓的,所以只要在不违反国家法律法规的前提下,这些手段都是可以用的,

不论是传统行业还是新兴的IT网络,我们都要重视品牌的营销。学会如何推销自己,用最少的成本获得最大的回报。

9FLASH的杨涛 一篇“9flash的流量是怎样练成的”文章,被众多站长拜读,不但营销了自己的9FLASH品牌。而且还增加了网站的流量。他所写的东西正是我们站长喜欢的。杨涛是个绝对聪明的人,他很早就注重自己网站品牌的营销,当初给自己的网站定了口号,打出“爱你就象老鼠爱大米”,他把他的心得写了出来。得到了大家的认可,在读者的心里有了烙印。他的品牌自然会提升。而他的文章也在各大媒体转载,包括新浪(http: //tech.sina.com.cn/i/2005-03-23/1729559535.shtml),否则一个个人站长怎能拿到某日本的华资企业数百万元的投资。

收购的公司看重的是9FLASH 的品牌,所以网站的价值品牌排在第一位,而内容则是在品牌之后的次重点。

那么,网络营销到底能起到什么的效果那,他们能解决你所遇到的哪些问题呢?我看他可以解决你的流量问题,增加网站知名度,给你带来很高的现金收入。

好123不外乎个人站长的顶峰之作,很多人认为李兴平是个善于营销的搞人。我不这么认为,他的成功是有偶然性,不可复制性的。我不否认他的成功,但是就品牌营销上他绝对是个弱者,李做网站N 年,其好123的盈利模式一直很单一,而李的性格内向,拒绝一切外来的合作者,而其在265组织的厦门站长大会上却是他这么多年第一次走出广东省,实在令人汗颜。而好123的价格网络上一直有传被千万收购,其实从李在厦门站长大会上的一番话。圈里人也都明白了百度拣了个大便宜,实在佩服李彦宏见缝就插的能力。

好123其实有更深的价值去挖掘,百度收购好123不是平白无故的,正是利用他在个人站长中的品牌优势,对百度产品进行更深层次的推广,而好123无疑是个很好的平台。

                         --转帖完毕