什么是抽象工厂模式:
抽象工厂模式是所有形态的工厂模式中最为抽象和最其一般性的。抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,能够创建多个产品族的产品对象。
还是先看看代码实现吧:
package com.product;
public interface Fruit {
public void get();
}
package com.product;
/**
* 抽象苹果类
* @author Owner
*
*/
public abstract class Apple implements Fruit{
}
package com.product;
/**
* 抽象香蕉类
* @author Owner
*
*/
public abstract class Banana implements Fruit{
}
package com.product;
/**
* 具体产品类,北方苹果类
* @author Owner
*
*/
public class NorthApple extends Apple {
@Override
public void get() {
System.out.println("采摘北方苹果类");
}
}
package com.product;
/**
* 北方香蕉类
* @author Owner
*
*/
public class NorthBanana extends Banana {
@Override
public void get() {
System.out.println("采摘北方香蕉");
}
}
package com.product;
/**
* 南方苹果类
* @author Owner
*
*/
public class SourthApple extends Apple {
@Override
public void get() {
System.out.println("采摘南方苹果");
}
}
package com.product;
/**
* 南方香蕉类
* @author Owner
*
*/
public class SourthBanana extends Banana {
@Override
public void get() {
System.out.println("采摘南方香蕉");
}
}
package com.product;
/**
* 水果工厂接口
* @author Owner
*
*/
public interface FruitFactory {
/**
* 获取苹果
*/
public Fruit getApple();
/**
* 获取香蕉
*/
public Fruit getBanana();
}
package com.product;
/**
* 对应的产品族,北方工厂类,主要生产北方苹果对象,和北方香蕉对象
* @author Owner
*
*/
public class NorthFactory implements FruitFactory {
@Override
public Fruit getApple() {
return new NorthApple();
}
@Override
public Fruit getBanana() {
return new NorthBanana();
}
}
package com.product;
/**
* 南方工厂类,主要生产南方苹果,和,南方香蕉
* @author Owner
*
*/
public class SourthFactory implements FruitFactory {
@Override
public Fruit getApple() {
return new SourthApple();
}
@Override
public Fruit getBanana() {
return new SourthBanana();
}
}
package com.product;
/**
* 顾客类
* @author Owner
*
*/
public class Customer {
public static void main(String[] args) {
//获取北方工厂,生产北方苹果实体和北方香蕉实体
FruitFactory northFactory = new NorthFactory();
Fruit northApple = northFactory.getApple();
Fruit northBanana = northFactory.getBanana();
northApple.get();
northBanana.get();
//同理,获取南方工厂,生产南方苹果实体和南方香蕉实体
FruitFactory sourthFactory = new SourthFactory();
Fruit sourthApple = sourthFactory.getApple();
Fruit sourthBanana = sourthFactory.getBanana();
sourthApple.get();
sourthBanana.get();
}
}
采摘北方苹果类
采摘北方香蕉
采摘南方苹果
采摘南方香蕉