目录
前言
首先实现工厂方法模式,这个模式有两种,为简单工厂和工厂方法模式。
简单工厂模式
UML
结构对象
1. 抽象产品类:提供抽象方法供具体产品类实现
2. 具体产品类:提供具体产品
3. 工厂:根据内部逻辑返回相应的产品
代码实现
1. 抽象产品类
public interface Tea {
void product();
}
2. 具体产品类
public class RedTea implements Tea{
@Override
public void product() {
System.out.println("红茶");
}
}
public class GreenTea implements Tea{
@Override
public void product() {
System.out.println("绿茶");
}
}
3. 工厂类
public class Factory {
public Tea getTea(String type){
Tea tea = null;
if("red".equals(type)){
tea = new RedTea();
}else if("green".equals(type)){
tea = new GreenTea();
}
return tea;
}
}
4. 测试类
public class TeaTest1 {
public static void main(String[] args) {
Factory factory = new Factory();
Tea red = factory.getTea("red");
red.product();
Tea green = factory.getTea("green");
green.product();
}
}
工厂方法模式
UML
结构对象
1. 抽象产品类:提供抽象方法供具体产品类实现
2. 抽象工厂:提供抽象方法供具体工厂实现
3. 具体产品类:提供具体的产品
4. 具体工厂:提供具体的工厂
代码实现
1. 抽象产品类
public interface Tea {
void product();
}
3. 抽象工厂
public interface IFactory {
Tea getFactory();
}
2. 具体产品类
public class GreenTea implements Tea {
@Override
public void product() {
System.out.println("绿茶");
}
}
public class RedTea implements Tea {
@Override
public void product() {
System.out.println("红茶");
}
}
4. 具体工厂
public class GreenFactoryImpl implements IFactory{
@Override
public Tea getFactory() {
return new GreenTea();
}
}
public class RedFactoryImpl implements IFactory{
@Override
public Tea getFactory() {
return new RedTea();
}
}
5. 测试类
public class TeaTest2 {
public static void main(String[] args) {
RedFactoryImpl redFactory = new RedFactoryImpl();
GreenFactoryImpl greenFactory = new GreenFactoryImpl();
Tea rf = redFactory.getFactory();
Tea gf = greenFactory.getFactory();
rf.product();
gf.product();
}
}
结束语
完成了工厂方法模式,接下来就要进行抽象方法工厂的实现了。