到 Google 资讯主页   
EasyJF首页   资料   源码   软件    论坛   网站    
   使用帮助    
    该信息为本站MyRSS系统缓存内容,部分图片及附件有可能无法正常使用.easyjf.comwww.javaresearch.org无关,不对该信息负责.通过http://www.javaresearch.org/article//showarticle.jsp?column=31&thread=48101访问该信息的原始内容.
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   
JAVA的设计模式 (1)
作者:cucumalo 来源:www.javaresearch.org  发布时间:2006-09-08 08:50:47.677


JAVA的设计模式经前人总结可以分为23种,希望在学习完毕后能对自己的工作有所帮助。

设计模式根据使用类型可以分为三种:

1、    创建模式:工厂模式、单子模式、建造者模式、原型模式、工厂方法模式。
2、    结构模式:外观模式、代理模式、适配器模式、组合模式、装饰模式、桥模式、
共享模式。
3、    行为模式:模板模式、纪念品模式、观察者模式、责任链模式、命令模式、声明模式、
            策略模式、中介模式、解释器模式、访问模式。

注:以上翻译不准确,还是以英文为准。

一、    创建模式:
1、    工厂模式(Factory),工厂方法模式(略):
工厂模式是我们最常用的模式了,著名的Jive论坛 ,就大量使用了工厂模式,工厂模式在Java程序系统可以说是随处可见。

工厂模式有好多种其中最常用的是简单的工厂模式,例如下

public class Factory{
          public static windows creator(int which){
          //getClass 产生Sample 一般可使用动态类装载装入类。
          if (which==1)    
        return new windows1 ();
          else if (which==2)
        return new windows2();
           }
              Public static void main(String []args){
       Windows = Factory.creator(1);
       Windows.fun();
}
}
Public Interface windows{
       Public abstract void fun();
}
Public class windows1 implements windows{
        Public void fun(){
               System.out.println(“hello am 1”);
}
}
Public class windows2 implements windows(){
        Public void fun(){
              System.out.println(“hello am 2”);
}
}
步骤:
1、    建立两个子类的公共接口方法。
2、    两个子类实现接口的方法。
3、    建立公共工厂类提供公共方法返回接口类型,参数是区别两个子类的依据。
4、    调用接口提供的公共方法,系统自动调用子类的方法。

2、    单子模式(Singleton):
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
例子一:
    import java.util.*;
    class Singleton{
          private static Singleton instance;
          private Vector v;
         private boolean inUse;

          private Singleton(){
                v = new Vector();
                v.addElement(new Object());
                inUse = true;
         }

          public static Singleton getInstance(){
                if (instance == null)          //1
                  instance = new Singleton();  //2
                return instance;               //3
          }
    }
     例子二:
public class SingletonSmple {
  
  private static SingletonSmple singleton = null;
  
  static {
        singleton = new SingletonSmple();
  }
  public  static synchronized  SingletonSmple getInstence() throws SingletonException {
         if(singleton == null){
                 singleton = new SingletonSmple();
         }
         return singleton ;
  }
}
class hello{
  public static void main(String[]args){
         for(int i =0 ; i< 2 ; i++){
                try {
                  System.out.println(SingletonSmple.getInstence());
                }
                catch (Exception ex) {
                }
         }
  }
}


 
相关文章
 
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   


EasyJF.com 2006 隐私政策 使用EasyJF前必读