定义:
- 也叫静态工厂模式;一个工厂对象决定创建出哪一种产品的实例(传入一个type,实例并执行type对应逻辑)最简单也是最实用的模式
- 通过专门定义一个类来负责创建其它类的实例,被创建的实例通常 都具有共同的父类。
- 工厂类是整个模式的关键所在。它包含必要的判断逻辑,能够根据外界给定的信息,决定究竟应该创建哪个具体类的对象。用户在使用时可以直接根据工厂类去创建所需的实例,而无需了解这些对象是如何创建以及如何组织的。有利于整个软件体系结构的优化
- 由于工厂类集中了所有实例的创建逻辑,所以“高内聚”方面做的并不好。另外,当系统中的具体产品类不断增多时,可能会出现要求工厂类也要做相应的修改,扩展性并不很好。在具体调用比较麻烦。
代码实现
public class Orange {
public void eat(){
System.out.println("吃橘子");
}
}
class Grape{
public void eat(){
System.out.println("吃葡萄");
}
}
class cilent{
public static void main(String[] args) {
Orange o =new Orange();
Grape g=new Grape();
o.eat();
g.eat();
}
}
可以发现A可以共同抽象出一个接口eat 修改代码如下
public class Orange implements Fruit{
@Override
public void eat(){
System.out.println("吃橘子");
}
}
class Grape implements Fruit{
@Override
public void eat(){
System.out.println("吃葡萄");
}
}
interface Fruit{
void eat();
}
class cilent{
public static void main(String[] args) {
Fruit o =new Orange();
Fruit g=new Grape();
o.eat();
g.eat();
}
}
按照定义:通过专门定义一个类来负责创建其他类的实例FruitFactory
public class Orange implements Fruit{
@Override
public void eat(){
System.out.println("吃橘子");
}
}
class Grape implements Fruit{
@Override
public void eat(){
System.out.println("吃葡萄");
}
}
interface Fruit{
void eat();
}
class FruitFactory{
public Fruit getOrange(){
return new Orange();
}
public Fruit getGrape(){
return new Grape();
}
}
class cilent{
public static void main(String[] args) {
Fruit o =new FruitFactory().getOrange();
Fruit g=new FruitFactory().getGrape();
o.eat();
g.eat();
}
}
那么我们有没有具体什么需要改进的地方?FruitFactory表明静态方法。这样就不用再新建实例化了。
class FruitFactory{
public static Fruit getOrange(){
return new Orange();
}
public static Fruit getGrape(){
return new Grape();
}
}
class cilent{
public static void main(String[] args) {
Fruit o = FruitFactory.getOrange();
Fruit g= FruitFactory.getGrape();
o.eat();
g.eat();
}
}
最终版,这部分代码的调用,比之前相比比较灵活了。
class FruitFactory {
public static Fruit getOrange() {
return new Orange();
}
public static Fruit getGrape() {
return new Grape();
}
public static Fruit getFruit(String name) throws Exception {
if (name.equals("Orange")) {
return Orange.class.newInstance();
} else if (name.equals("Grape")) {
return Grape.class.newInstance();
} else {
System.out.println("没有这个,你再检查一下有没有问题");
return null;
}
}
}
class cilent {
public static void main(String[] args) throws Exception{
Fruit o = FruitFactory.getFruit("Orange");
Fruit g = FruitFactory.getFruit("Grape");
o.eat();
g.eat();
}
}