工厂模式和抽象工厂模式
工厂方法适用于以下场景:
1、创建对象需要大量重复的代码。
2、客户端(应用层)不依赖于产品类实例如何被创建、实现等细节。
3、一个类通过其子类来指定创建哪个对象。
工厂方法也有缺点:
1、类的个数容易过多,增加复杂度。
2、增加了系统的抽象性和理解难度。
public class Test {
public static void main(String[] args) {
//简单工厂
TeaFactory teaFactory = new TeaFactory();
teaFactory.test(1).test();
Factory factory = new Factory1();
factory.test();
factory = new Factory2();
factory.test();
//工厂方法
ITeaFactory iTeaFactory = new ITeaFactory1();
iTeaFactory.factory().test();
iTeaFactory = new ITeaFactory2();
iTeaFactory.factory().test();
//抽象工厂
//创建A、B两接口,由AA、AB去实现A接口,BA、BB去实现B接口,然后创建C接口,接口回参方法分别为A、B,然后再创建CA、CB去实现C接口,由此抽象工厂完成
Count count = new CountModel();
count.tof().toTest();
count.inf().inTest();
Count count1 = new CountModel1();
count1.inf().inTest();
count1.tof().toTest();
}
}
//简单工厂
public class TeaFactory {
public Factory test(Integer type){
Factory factory;
if(type == 1){
factory = new Factory1();
}else {
factory = new Factory2();
}
return factory;
}
}
public class Factory1 implements Factory{
@Override
public void test() {
System.out.println("生产1");
}
}
public class Factory2 implements Factory{
@Override
public void test() {
System.out.println("测试2");
}
}
//方法工厂
public interface ITeaFactory {
public Factory factory();
}
public class ITeaFactory1 implements ITeaFactory{
@Override
public Factory factory() {
return new Factory1();
}
}
public class ITeaFactory2 implements ITeaFactory{
@Override
public Factory factory() {
return new Factory2();
}
}
//抽象工厂
public interface InFactory {
void inTest();
}
public class InFile implements InFactory{
@Override
public void inTest() {
System.out.println(" in file");
}
}
public class InModel implements InFactory{
@Override
public void inTest() {
System.out.println("in model ");
}
}
public interface ToFactory {
void toTest();
}
public class ToFile implements ToFactory{
@Override
public void toTest() {
System.out.println("to file");
}
}
public class ToModel implements ToFactory{
@Override
public void toTest() {
System.out.println("to model");
}
}
public interface Count {
InFactory inf();
ToFactory tof();
}
public class CountModel implements Count{
@Override
public InFactory inf() {
return new InFile();
}
@Override
public ToFactory tof() {
return new ToFile();
}
}
public class CountModel1 implements Count{
@Override
public InFactory inf() {
return new InModel();
}
@Override
public ToFactory tof() {
return new ToModel();
}
}