随笔 - 40, 文章 - 0, 评论 - 20, 引用 - 0
数据加载中……

Ibatis示例


1.将ibatis 的jar 包添加到工程中

2.先新建一个xml文件 SqlMap.xml,在这个文件中定义使用了哪些ibatis资源文件
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE sql-map-config PUBLIC "-//iBATIS.com//DTD SQL Map Config 1.0//EN"
    "http://www.ibatis.com/dtd/sql-map-config.dtd">
<sql-map-config>
  <sql-map  resource="com/montersoft/ibatis/common/monter.xml"/>
</sql-map-config>

3.定义资源文件monter.xml
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE sql-map
    PUBLIC "-//iBATIS.com//DTD SQL Map 1.0//EN"
    "http://www.ibatis.com/dtd/sql-map.dtd">
<sql-map name="monter">
   <result-map name="monterInfo" class="java.util.HashMap">
     <property name="id"  column="id" type="VARCHAR"/>
     <property name="name" column="name" type="VARCHAR"/>
     <property name="age"  column="age"  type="NUMBERIC"/>
   </result-map>  
   <dynamic-mapped-statement name="monter_getByPk" result-map="monterInfo">
   select id,name,age from monter where id = #id#
   </dynamic-mapped-statement>
</sql-map>

**注意dynamic-mapped-statement的name 必须唯一

4.定义一个公共类来生成SqlMap
package com.montersoft.ibatis.common;
import java.io.Reader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ibatis.common.resources.Resources;
import com.ibatis.db.sqlmap.SqlMap;
import com.ibatis.db.sqlmap.XmlSqlMapBuilder;
public class SqlMapUtil { 
 private static Log loger = LogFactory.getLog(SqlMapUtil.class);
 public  static SqlMap  sqlMap ; 
 public static SqlMap loadSqlMap(){
  Reader reader = null;
  try{
   reader = Resources.getResourceAsReader("com/montersoft/ibatis/common/SqlMap.xml");
   return XmlSqlMapBuilder.buildSqlMap(reader);
  }
  catch(Exception e){   
   loger.error("there is a error=>"+e.getMessage());
  }
  return null;
 } 
 public static SqlMap getSqlMap(){
  if( sqlMap == null )
   sqlMap = loadSqlMap();
  return sqlMap;
 } 
}
5.再新建DAO,Vo,
public interface  IVO { 
}
public class MonterVo implements IVO{ 
 public String id ;
 public String name;
 public int age;
 ...省去 get ,set 方法
}
public class MonterDao { 
   public IVO getBkPK(Connection conn,IVO vo) throws Exception{
    try{    
    Object map  =  SqlMapUtil.getSqlMap().
       getMappedStatement("monter_getByPk").executeQueryForObject(conn,vo);
    return   copyMap2Vo(map);
    }
    catch(Exception e){       
        throw new Exception(e.getMessage());
    }
   }  
   private IVO copyMap2Vo(Object map){
    MonterVo vo = new MonterVo();
  try{
   BeanUtils.copyProperties(vo,map);
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return vo;
 }
}

6.至此就建立了一个简单的ibatis示例.

posted @ 2006-01-06 16:39 月亮 阅读(326) | 评论 (0)编辑 收藏

通过weblogic的数据源获得数据库连接的方法

通过weblogic的数据源获得数据库连接的方法:

package com.moonsoft.datasource;

import javax.naming.NamingException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestDataSource {

  public static String WEB_URL = "t3://localhost:9000";
  public static String DATA_SOURCE = "JDBCDS";
  public static String weblogic_context_factory =
      "weblogic.jndi.WLInitialContextFactory";
  public TestDataSource() {
  }
  public static Object lookUp() throws NamingException {
    Hashtable env = new Hashtable();
    env.put(InitialContext.INITIAL_CONTEXT_FACTORY, weblogic_context_factory);
    env.put(InitialContext.PROVIDER_URL, WEB_URL);
    InitialContext tempContext = new InitialContext(env);
    return tempContext.lookup(DATA_SOURCE);
  }
  public static Connection getConnection() throws SQLException {
    Connection conn = null;
    try {
      DataSource ds = (DataSource) lookUp();
      if (ds == null) {
        throw new SQLException("查询到空数据源!");
      }
      conn = ds.getConnection();
    }
    catch (NamingException ex) {
      ex.printStackTrace();
    }
    return conn;
  }
  public static void releaseConnection(Connection conn, PreparedStatement sta,
                                       ResultSet rs) {
    try {
      if (rs != null) {
        rs.close();
      }
      if (sta != null)
        sta.close();
      if (conn != null)
        conn.close();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public static void testSearch() {
    Connection conn = null;
    PreparedStatement sta = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      String sql = "select * from admin_config where config_name like ?";
      sta = conn.prepareStatement(sql);
      sta.setString(1,"%Sms%");
      rs = sta.executeQuery();
      if (rs != null) {
        while (rs.next()) {
          System.out.println(rs.getString(1));
        }
      }
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    finally {
      releaseConnection(conn,sta,rs);
    }
  }
  public static void main(String [] argv){
    testSearch();
  }
}

posted @ 2006-01-05 10:51 月亮 阅读(1236) | 评论 (0)编辑 收藏

一个设计中使用比较多的模式

如果是在需求还没确定或者是在两个类实现相近功能时候,会大量使用下面的方式:
--抽象类,注意其中的newInstance方法的实现
package com.moonsoft.design;
public  abstract class Moon {
  public static Moon newInstance(String classStr){
    Class re;
    try {
      re =  Class.forName(classStr);
      return (Moon)re.newInstance();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }
  public abstract void  println();
}
--从Moon类派生出来的一个字类,提供println方法的一种实现方式
package com.moonsoft.design;
public class Moon1 extends Moon {
  public void println(){
    System.out.println("I am moon1");
  }
  public void myprintln(){
    System.out.println("I am moon1 myprintln");
  }
}
--从Moon类派生出来的另一个字类,提供println方法的另一种实现方式
package com.moonsoft.design;
public class Moon2 extends Moon {
   public void println(){
    System.out.println("I am moon2!");
  }
}
--调用
 Moon moon = Moon.newInstance("com.moonsoft.design.Moon1");
 moon.println();
 或
 Moon moon = Moon.newInstance("com.moonsoft.design.Moon2");
 moon.println();

posted @ 2006-01-04 16:41 月亮 阅读(97) | 评论 (0)编辑 收藏

JSP标签的使用方法


如要在JSP页面上有一个链接,Url值是通过参数输入的,用JSP标签的实现步骤(当然实际中不会用标签来完成这么简单的功能):

<一>.先从javax.servlet.jsp.tagext.BodyTagSupport派生一个新的类,并重载它的doStartTag()方法.如果是想要传入参数的话,则还要在Bean中加入想要的变量,如这里要传入一个url值,所以添加一个参数:linkUrl. 最后代码如下:

package com.moonsoft.jsptag;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspException;
public class UrlLinkTag extends BodyTagSupport  {
  private String linkUrl;
  public UrlLinkTag() {
  }
  public String getLinkUrl() {
    return linkUrl;
  }
  public void setLinkUrl(String linkUrl) {
    this.linkUrl = linkUrl;
  }
  public int doStartTag() throws JspException{
    try {
      this.pageContext
          .getOut().print("<a href=\'"+linkUrl+"\' >"+linkUrl+"</a>");
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    return 0;
  }
}

<二>新建一个tld文件,内容如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
 "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
 <taglib>
        <tlibversion>1.0</tlibversion>
 <jspversion>1.1</jspversion>
 <shortname>buttons</shortname>
 <uri>http://www.borland.com/jbuilder/internetbeans.tld</uri>
 <info>
 JSP tag extensions for InternetBeans Express
  </info>
    <tag>
 <name>urllink</name>
 <tagclass>com.moonsoft.jsptag.UrlLinkTag</tagclass>
 <bodycontent>jsp</bodycontent>
 <attribute>
  <name>linkUrl</name>
  <required>true</required>
  <rtexprvalue>true</rtexprvalue>
 </attribute>
    </tag>
   </taglib>
  
<三>在web.xml中引入这个taglib,在其中加入:

<taglib>
    <taglib-uri>/moon</taglib-uri>
    <taglib-location>/WEB-INF/classes/com/moonsoft/jsptag/UrlLinkTag.tld</taglib-location>
</taglib>


<四>在jsp中引入这个标签
<%@ taglib uri="/moon" prefix="mylinkurl" %>
这里uri是和web.xml中配置的taglib-uri对应的,prefix值只是在本jsp页面作为标示用.

下面就可以在jsp中使用这个标签了:

<mylinkurl:urllink linkUrl="http://www.baidu.com" />

这里面的mylinkurl为在本jsp页面中设置的prefix值,urllink为tld文件中tag name,linkUrl为输入的参数

这样就在jsp页面上加入了一个:
<a href='http://www.baidu.com' >http://www.baidu.com</a>链接

posted @ 2005-12-29 13:47 月亮 阅读(1423) | 评论 (0)编辑 收藏

Java Excel 使用攻略

 现在正在做的项目中涉及大量的Excel文件导出导入操作,都是使用Java Excel来操作。

Java Excel是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容、创建新的Excel文件、更新已经存在的Excel文件。下面我写了一个简单的例子,展示基本的读取,新建,更新(包括常见格式的设置:字体,颜色,背景,合并单元格),拷贝操作,有这些其实已经基本足够应付大部分问题了。下面是例的源代码:

import java.io.*;
import java.util.Date;

import jxl.*;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.format.UnderlineStyle;
import jxl.format.CellFormat;;

public class OperateExcel {
 
 /**
  * Read data from a excel file
  */
 public static void  readExcel(String excelFileName){
  Workbook  rwb = null;  
  try{
   InputStream stream = new FileInputStream(excelFileName);
   rwb = Workbook.getWorkbook(stream);
   Sheet  sheet = rwb.getSheet(0);
   Cell   cell  = null;
   int columns = sheet.getColumns();
   int rows    = sheet.getRows();
   for( int i=0 ; i< rows ; i++ )
    for( int j=0 ; j< columns ; j++){
     //attention: The first parameter is column,the second parameter is row.  
     cell = sheet.getCell(j,i);    
     String str00 = cell.getContents();
     if( cell.getType() == CellType.LABEL )
       str00 += " LAEBL";
     else if( cell.getType() == CellType.NUMBER)
       str00 += " number";
     else if( cell.getType() == CellType.DATE)
       str00 += " date"; 
     System.out.println("00==>"+str00);
    } 
   stream.close();
  }
  catch(IOException e){  
   e.printStackTrace();
  }
  catch(BiffException e){
   e.printStackTrace();
  } 
  finally{  
   rwb.close();
  }
 }
 /**
  * create a new excelFile
  * @param excelFileName create name
  */
 public static void createExcelFile(String excelFileName){
  try{
   WritableWorkbook wwb = Workbook.createWorkbook(new File(excelFileName));
   WritableSheet     ws  = wwb.createSheet("sheet1",0);
   //also,The first parameter is  column,the second parameter is row.
   // add normal label data
   Label label00 = new Label(0,0,"Label00");
   ws.addCell(label00);
   //add font formating data   
   WritableFont  wf = new WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD , true);
   WritableCellFormat wff = new WritableCellFormat(wf);
   Label label10 = new Label(1,0,"Label10",wff);
   ws.addCell(label10);
   //add color font formating data
   WritableFont wf_color = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,Colour.RED);
   WritableCellFormat wff_color = new WritableCellFormat(wf_color);
   wff_color.setBackground(Colour.GRAY_25); //set background coloe to gray  
   Label label20 = new Label(2,0,"Label20",wff_color);   
   ws.addCell(label20);
   
   //合并单元格
   WritableFont wf_merge = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,Colour.GREEN);
   WritableCellFormat wff_merge = new WritableCellFormat(wf_merge);
   wff_merge.setBackground(Colour.BLACK);
   Label label30 = new Label(3,0,"Label30",wff_merge);   
   ws.addCell(label30);
   Label label40 = new Label(4,0,"Label40");
   ws.addCell(label40);
   Label label50 = new Label(5,0,"Label50");
   ws.addCell(label50);
     //合并 (0,3) (4,0)
     //attention : 如果合并后面的列不为空,那么就把后面格的内容清空,格式也是按前一个单元格的格式
   ws.mergeCells(3,0,4,0);
   
   //添加Number格式数据
   jxl.write.Number labelN = new jxl.write.Number(0, 1, 3.1415926);
   ws.addCell(labelN);
   
   //添加带有formatting的Number对象
   jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
   jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
   jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
   ws.addCell(labelNF);
   
   //添加Boolean对象
   jxl.write.Boolean labelBoolean = new jxl.write.Boolean(2,1,false);
   ws.addCell(labelBoolean);
   
   //添加DateTime对象
   DateTime labelDT = new DateTime(3,1,new Date());
   ws.addCell(labelDT);
   
   //添加带有格式的DataTime数据
   DateFormat dtf = new DateFormat("yyyy-MM-dd hh:mm:ss");
   WritableCellFormat wcfDt = new WritableCellFormat(dtf);   
   wcfDt.setBackground(Colour.YELLOW);
   DateTime labelDT_format =  new DateTime(4,1,new java.util.Date(),wcfDt);
   ws.addCell(labelDT_format);
   ws.mergeCells(4,1,5,1); //比较长,用两列来显示     
   
   wwb.write();
   wwb.close();
  }
  catch(IOException e){
   e.printStackTrace();
  }
  catch(WriteException e){
   e.printStackTrace();
  }  
 }
 /**
  * 如何更新Excel文件
  * @param fileName
  */
 public static void updateExcel(String fileName){  
  try{
   jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(fileName));
   WritableWorkbook wwb = Workbook.createWorkbook(new File(fileName),rw);
   //这里其实执行的是一次copy操作,把文件先读到内存中,修改后再保存覆盖原来的文件来实现update操作
   WritableSheet ws  = wwb.getSheet(0);
   WritableCell wc = ws.getWritableCell(0,0);
   if( wc.getType() == CellType.LABEL){
    Label l = (Label)wc;
    l.setString(wc.getContents()+"_new");
   }
   wwb.write();
   wwb.close();
  }
  catch(IOException e){
   e.printStackTrace();
  }
  catch(WriteException e){
   e.printStackTrace();
  } 
  catch(BiffException e){
   e.printStackTrace();
  }
 }
 /**
  * 如何copy Excel文件
  * @param fileName
  */
 public static void copyExcel(String sourFileName,String destFileName){  
  try{
   jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(sourFileName));
   WritableWorkbook wwb = Workbook.createWorkbook(new File(destFileName),rw);
   wwb.write();
   wwb.close();
  }
  catch(IOException e){
   e.printStackTrace();
  }
  catch(WriteException e){
   e.printStackTrace();
  } 
  catch(BiffException e){
   e.printStackTrace();
  }
 }
 
 public static void main(String [] argv){
  //OperateExcel.readExcel("E:\\test.xls");
  //OperateExcel.createExcelFile("E:\\test1.xls");
  //OperateExcel.updateExcel("E:\\test.xls");
  OperateExcel.copyExcel("E:\\test.xls","E:\\moon.xls");
 }

}


posted @ 2005-12-06 15:06 月亮 阅读(2192) | 评论 (4)编辑 收藏

执行过程中动态执行方法

在编程中可能回碰到一些到实际运行时才指定要调用的方法的需要,最典型的是Struct的DispatchAction类,
它能根据用户页面请求参数的不同来调用不同的方法来处理用户请求。我下面写了一个简单的例子来简单演示其
实现方法:

package learn;
import java.lang.NoSuchMethodException;
import java.lang.reflect.Method;
import java.util.Date;

public class TestMethod{
    protected Class clazz = this.getClass();
    protected Class[] no_parameter = {};  //方法无参数
    protected Class[] string_parameter = {String.class}; //以String 为参数
    protected Class[] int_parameter = {int.class};  //以int为参数
    protected Class[] multi_parameter = {String.class,Date.class}; //多个参数,第一个为String,第二二个为Date   
   
    public void method1(){
      System.out.println("method1");
    }
   
    public void method2(String str){
      System.out.println("method2=>"+str);
    }
   
    public void method3(int i){
      System.out.println("method2=>"+i);
    }
   
    public void method4(String str,Date date){
      System.out.println("method4=>"+str+"==="+date.toLocaleString());
    }
   
    public void execute(String methodName,int type,java.util.List list) throws Exception{
      try {
        Method  m = getMethod(methodName,type);
        int size = (list != null )? list.size():0;
        Object o [] = new Object[size];
        for( int i =0 ; i< size ; i++ )
          o[i] = list.get(i);  //准备参数
        m.invoke(this,o);
      }
      catch (Exception ex) {
        ex.printStackTrace();
        throw new Exception(ex.getMessage());
      }
    }
   
    private Method getMethod(String name,int type)throws NoSuchMethodException{
        Method m = null;
        switch(type){
          case 1:
            m = clazz.getMethod(name,no_parameter);
            break;
          case 2:
            m = clazz.getMethod(name,string_parameter);
            break;
          case 3:
            m = clazz.getMethod(name,int_parameter);
            break;
          case 4:
            m = clazz.getMethod(name,multi_parameter);
            break;
          default:
            m = clazz.getMethod(name,no_parameter);
        }
        return m;
    }
   
    public static void main(String [] argv){
      TestMethod testMethod = new TestMethod();
      try{
        java.util.List list = new java.util.ArrayList();
        testMethod.execute("method1", 1, list);
        list.add("
http://www.blogjava.net/minmoon");
        testMethod.execute("method2", 2, list);
        list.clear();
        list.add("
mailTo:xiaoliang@aspire-tech.com");
        list.add(new Date());
        testMethod.execute("method4",4,list);
      }
      catch(Exception e){
        e.printStackTrace();
      }
    }
}

其中几个关键的地方说明一下:
  clazz.getMethod(name,multi_parameter);  其中multi_parameter是要根据实际方法的参数来定义的。
  m.invoke(this,o);   o是要传入方法的参数列表。

posted @ 2005-11-23 00:18 月亮 阅读(480) | 评论 (0)编辑 收藏

23种面向对象的设计模式----Prototype模式


原型模式定义:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.

Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。

如何使用?
因为Java中的提供clone()方法来实现对象的克隆,所以Prototype模式实现一下子变得很简单.

以勺子为例:

public abstract class AbstractSpoon implements Cloneable
{
  String spoonName;

  public void setSpoonName(String spoonName) {this.spoonName = spoonName;}
  public String getSpoonName() {return this.spoonName;}

  public Object clone()
  {
    Object object = null;
    try {
      object = super.clone();
    } catch (CloneNotSupportedException exception) {
      System.err.println("AbstractSpoon is not Cloneable");
    }
    return object;
  }
}

有个具体实现(ConcretePrototype):

public class SoupSpoon extends AbstractSpoon
{
  public SoupSpoon()
  {
    setSpoonName("Soup Spoon");
  }
}

调用Prototype模式很简单:

AbstractSpoon spoon = new SoupSpoon();
AbstractSpoon spoon2 = spoon.clone();

当然也可以结合工厂模式来创建AbstractSpoon实例。

在Java中Prototype模式变成clone()方法的使用,由于Java的纯洁的面向对象特性,使得在Java中使用设计模式变得很自然,两者已经几乎是浑然一体了。这反映在很多模式上,如Interator遍历模式。



原文出处:http://www.jdon.com/designpatterns/prototype.htm

看看写的很好,就拿来引用一下,不用自己写的那么累^_^.

posted @ 2005-11-20 20:32 月亮 阅读(200) | 评论 (0)编辑 收藏

23种面向对象的设计模式----Factory method模式


Factory method,工厂方法模式,定义一个用于创建对象的接口,让字类决定实例化哪一个类。也就是使一个类的实例化延迟到其子类,提供一种方法使对象创建变得多态。
下面是我写的一个例子,如有两种工人,car worker和bus worker,所生成的产品分别是car 和 bus,我按照Factory method 的实现如下:


--先定义car 和 bus 的父类,都是一种产品
package Factory;
public class Product {
 
 public  void whoami(){
  System.out.println("I am a product!");
 }
}

--Car 类
package Factory;
public class Car extends Product { 
 public Car() {
 } 
 public void whoami(){
  System.out.println("I am a car!");
 } 
}
--Bus 类
package Factory;
public class Bus extends Product { 
 public Bus() {
 } 
 public void whoami(){
  System.out.println("I am a bus!");
 }
}
--定义CarWorker和BusWorker的父类 worker
package Factory;
public abstract class Worker { 
 private Product theProduct;
 public abstract Product  createProduct(); 
 public void work(){
  theProduct = createProduct();
 }
 public void showMessage(){
  this.theProduct.whoami();
 }
}
--Carworker
package Factory;
public class CarWorker extends Worker { 
 public Product createProduct(){
   return new Car();
 }
}
--BusWorker
package Factory;
public class BusWorker extends Worker { 
 public Product  createProduct(){
  return new Bus();
 }
}
--下面看看具体的调用
package Factory;
public class TestAll {

 public static void main(String [] argv){ 
  Worker  worker = new CarWorker();
  worker.work();
  worker.showMessage();
  
  Worker  worker1 = new BusWorker();
  worker1.work();
  worker1.showMessage(); 
 } 
}
可以看到虽然这样实现有一些麻烦,如新加一种产品时,就必须从Product类创建一个子类,但是这样做的
好处也是显而易见的,会给你系统带来更大的可扩展性和尽量少的修改量,再添加一种产品一种工人的时候,对以前的代码是不必做任何修改的。

<个人观点,仅作参考>

 

posted @ 2005-11-13 21:35 月亮 阅读(916) | 评论 (1)编辑 收藏

23种面向对象的设计模式----Singleton模式

  Singleton模式为单态模式或者叫孤子模式,保证一个类只有一个实例,并提供一个访问它的全局访问点。
  Singleton模式的使用范围比较广泛,对于一些类来说,只有一个实例是很重要的。比如,你要论坛中

的帖子计数器,每次浏览一次需要计数,单态类能否保持住这个计数,并且能synchronize的安全自动加

1,如果你要把这个数字永久保存到数据库,你可以在不修改单态接口的情况下方便的做到。
下面是一个简单的示例程序:
package Singleton;
public class TestSingleton { 
 private static TestSingleton  testSingleton = null;
 protected int  count = 0; 
 public static synchronized  TestSingleton getInstance(){
   if( testSingleton ==   null)
    testSingleton = new TestSingleton();
   return testSingleton;
 }
 public void addCount(){
  count ++;
 }
 public void showCount(){
  System.out.println("count :"+count);
 }  
}
我们还可以在这个基础上做一个扩展,如从上面例子中的TestSingleton类扩展出多个子类,在

getInstance方法中控制要使用的是哪个子类,具体实现代码如下:

-----TestSingleton.java
package Singleton;
public class TestSingleton { 
 private static TestSingleton  testSingleton = null;
 protected int  count = 0; 
 public static synchronized  TestSingleton getInstance(){
   if( testSingleton ==   null)
    testSingleton = new SubTestSingleton ();
   return testSingleton;
 }
 public void addCount(){
  count ++;
 }
 public void showCount(){
  System.out.println("TestSingleton count :"+count);
 }  
}

-----SubTestSingleton.java
public class SubTestSingleton extends TestSingleton{
 public void showCount(){
  System.out.println("SubTestSingleton count :"+count);
 }
}

<以上为个人见解,欢迎大家评论!>

posted @ 2005-11-13 15:54 月亮 阅读(660) | 评论 (0)编辑 收藏

面向对象的23种设计模式

  最近对面向对象的设计的23种经典的设计模式做了一个研究,接下来的Blog中我会按我的理解做个简单介绍并提供我写的示例代码,欢迎大家的评论,共同提高.
  
   

posted @ 2005-11-13 15:40 月亮 阅读(752) | 评论 (0)编辑 收藏

仅列出标题
共4页: 上一页 1 2 3 4 下一页