vjame

优化代码是无止境的
随笔 - 65, 文章 - 9, 评论 - 26, 引用 - 0
数据加载中……

单态模式和简单工厂模式

单态模式
 Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
在项目的很多地方都会用到它,比如说数据库的链接。
使用Singleton的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收。

1. 编写代码
package com.strongit.singleton;


class A {
    
private static final A a = new A();
    
public static A getSingleInstance(){
        
return a;
    }
    
public void say(){
        System.out.println(
"hello");
    }
}

public class SingletonDemo {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
            A a = A.getSingleInstance();
            a.say();
            System.out.println(A.getSingleInstance());

            System.out.println(A.getSingleInstance());
        
    }

}

2.运行结果
hello...
com.strongit.singleton.A@1c78e57
com.strongit.singleton.A@1c78e57


简单工厂模式
简单工厂模式又叫静态工厂模式,顾名思义,它是用来实例化目标类的静态类。下面我主要通过一个简单的实例说明简单工厂及其优点。 

package com.strongit.factory;


//抽象汽车
interface Car{
    
public void run();
    
public void stop();
}

//奔驰汽车
class Benz implements Car{
    
public void run() {
        System.out.println(
"BMW run ");
    }

    
public void stop() {
        System.out.println(
"BMW stop  ");
    }
}

//福特汽车
class Ford implements Car{

    
public void run() {
        System.out.println(
"Ford run ");
    }
    
public void stop() {
        System.out.println(
"Ford stop ");
    }
    
}

//工厂帮助客服返回实例化对象
class Factory{
    
public static Car getCarInstance(String type){
        Car car 
= null;
        
try {
            
//java反射机制
            car = (Car)Class.forName("com.strongit.factory."+type).newInstance();
        } 
catch (InstantiationException e) {
            e.printStackTrace();
        } 
catch (IllegalAccessException e) {
            e.printStackTrace();
        } 
catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        
return car;
    }
}


//客服端调用
public class FactoryDemo {

    
public static void main(String[] args) {
        String type 
= "Ford";
        Car car 
= Factory.getCarInstance(type);
        
if(car == null){
            System.out.println(
"error ");
        }
else{
            car.run();
        }
    }
}

posted on 2008-10-30 16:47 lanjh 阅读(281) 评论(0)  编辑  收藏 所属分类: 设计模式


只有注册用户登录后才能发表评论。


网站导航: