您的位置:首页 > 编程语言 > Java开发

Java工厂设计模式

2016-03-04 10:51 591 查看
程序在接口和子类之间加入一个过渡类,通过此过渡类端取得接口的实例化对象,一般都会称这个过渡端为工厂类

//=================================================
// File Name       :	factory
//------------------------------------------------------------------------------
// Author          :	Common

// 接口名:Fruit
// 属性:
// 方法:
interface Fruit{
public void eat();
}

//类名:Apple
//属性:
//方法:
class Apple implements Fruit{

@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println("eat apple!");
}

}

//类名:Orange
//属性:
//方法:
class Orange implements Fruit{

@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println("eat orange!");
}

}

//类名:Factory
//属性:
//方法:
class Factory{												//定义工厂类
public static Fruit getInstance(String className){
Fruit f = null;											//定义接口对象
if("apple".equals(className)){			//判断是哪个类的标记
f = new Apple();
}
if("orange".equals(className)){			//判断是哪个类的标记
f = new Orange();
}
return f;

}
}

//主类
//Function        : 	工厂设计模式
public class factory {

public static void main(String[] args) {
// TODO 自动生成的方法存根
Fruit f = null;										//定义接口对象
f = Factory.getInstance("apple");		//通过工厂取得实例
f.eat();													//调用方法
}

}




//=================================================
// File Name       :	factory
//------------------------------------------------------------------------------
// Author          :	Common

// 接口名:Fruit
// 属性:
// 方法:
interface Fruit{
public void eat();
}

//类名:Apple
//属性:
//方法:
class Apple implements Fruit{

@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println("eat apple!");
}

}

//类名:Orange
//属性:
//方法:
class Orange implements Fruit{

@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println("eat orange!");
}

}

//类名:Factory
//属性:
//方法:
class Factory{												//定义工厂类
public static Fruit getInstance(String className){
Fruit f = null;											//定义接口对象
try{
f = (Fruit)Class.forName(className).newInstance();	//实例化对象
}catch(Exception e){
e.printStackTrace();
}
return f;

}
}

//主类
//Function        : 	工厂设计模式
public class factory {

public static void main(String[] args) {
// TODO 自动生成的方法存根
Fruit f = null;										//定义接口对象
f = Factory.getInstance("Apple");		//通过工厂取得实例
f.eat();													//调用方法
}

}


结合属性文件的工厂模式





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: