2.工厂方法模式

定义

工厂方法模式也是我们使用频率相当高的模式
定义:定义一个用于创建对象的接口,让子类来决定实例化那一个类;工厂方法使一个类的实例化延迟到其子类

通用源码

在工厂方法模式中,会存在几个类:

  1. 抽象产品类Product负责定义所要生产的产品的共性,实现对事物最抽象的定义
  2. 抽象创建类Creator,也就是我们所谓的抽象工厂
  3. 实现工厂类ConcreteCreator,具体如何创建产品类由它来实现

通用源码如下:

//抽象产品类
public abstract class Product {
	//产品类的公共方法---共性
	public void method1() {
		...//业务逻辑
	}
	//抽象方法---特性
	public abstract void method2();
}

//具体产品类  具体的产品类可以很多,都继承与抽象产品类
public class ConcreteProduct1 extends Product {
	//重写抽象方法
	public void method2() {
		...//业务逻辑
	}
}
public class ConcreteProduct2 extends Product {
	//重写抽象方法
	public void method2() {
		...//业务逻辑
	}
}

//抽象工厂类  抽象工厂类负责定义产品实例的产生
public abstract class Creator {
	//创建产品实例的抽象方法,其输入参数自行设置,可是String/Class等
	public abstract <T extends Product> T createProduct(Class<T> c);
}

//具体工厂类  具体工厂类负责具体生产每个产品
public class ConcreteCreator extends Creator {
	public <T extends Product> T createProduct(Class<T> c) {
		Product product = null;
		try {
			product = (Product) Class.forName(c.getName()).new Instance();
		} catch (Expection e) {
			...//异常处理
		}
		return (T) product;
	}
}

//场景类
public class Client {
	public static void main(String[] args) {
		Creator creator = new ConcreteCreator();
		Product product = creator.createProduct(ConcreteProduct1.class);
		...//业务逻辑
	}
}

应用

优点

  1. 良好的封装性,代码结构清晰:如果需要一个类,只需要知道这个类的类名,就可以创建,降低了模块间的耦合
  2. 扩展性十分优秀:在增加产品的情况下,只需要适当修改具体工厂或是扩展一个工厂就可以“拥抱变化”
  3. 屏蔽产品类:不管产品怎么变化,调用者都不用关心,只要接口不变就可以
  4. 工厂方法模式是典型的解耦框架

使用场景

  1. 工厂方法模式就是用于去代替直接的new出一个对象,所以在任何需要生成对象的地方都可以使用,但是也要根据实际情况考虑增加一个工厂类进行管理,也会增加代码的复杂性
  2. 需要灵活且方便扩展的框架时,也可以考虑使用工厂方法模式
  3. 可用于异构项目(如通过WebService与非java项目交互
  4. 可以用在测试驱动开发的框架下

扩展

  1. 将工厂方法模式缩小为简单工厂模式:我们一个模块仅需要一个工厂,那么我们可以产生工厂而使用静态方法来代替,例如不要抽象工厂类,而将具体工厂类中的create方法设置为静态方法;该模式是工厂方法模式的弱化,可叫简单方法模式也可以叫静态方法模式
  2. 扩展为多个工厂类:较为复杂的项目中我们可以不去传Class等相关参数,而是每一个具体的工厂明确负责一个产品,但也要注意其复杂度
  3. 代替单例模式:单例模式的核心要求就是在内存中只有一个对象,通过工厂方法模式也可以只在内存中生产一个对象
  4. 延迟初始化:一个对象被使用完后,并不立刻释放内存,工厂类保存其初始状态,等待被再次使用

总结

工厂方法模式在项目中实际使用的很频繁,且还会和其他的模式混合使用,要多多熟悉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,作为人工智能,我无法编写和运行Java代码。但是,我可以提供一些关于创建型设计模式的解释和示例,帮助你更好地理解这些概念。 1. 简单工厂模式 简单工厂模式是一种通过一个工厂类来创建不同类型对象的设计模式。在这种模式中,客户端只需要知道所需产品的名称或类型,而不需要知道具体的实现细节。 示例代码: ``` public class AnimalFactory { public static Animal createAnimal(String type) { if (type.equals("dog")) { return new Dog(); } else if (type.equals("cat")) { return new Cat(); } else { return null; } } } public interface Animal { public void makeSound(); } public class Dog implements Animal { public void makeSound() { System.out.println("Woof!"); } } public class Cat implements Animal { public void makeSound() { System.out.println("Meow!"); } } public class Main { public static void main(String[] args) { Animal animal1 = AnimalFactory.createAnimal("dog"); Animal animal2 = AnimalFactory.createAnimal("cat"); animal1.makeSound(); // Output: Woof! animal2.makeSound(); // Output: Meow! } } ``` 2. 工厂方法模式 工厂方法模式是一种将对象的创建委托给子类的设计模式。在这种模式中,客户端只需要知道所需产品的抽象类型,而具体的实现由子类来决定。 示例代码: ``` public interface Animal { public void makeSound(); } public class Dog implements Animal { public void makeSound() { System.out.println("Woof!"); } } public class Cat implements Animal { public void makeSound() { System.out.println("Meow!"); } } public abstract class AnimalFactory { public abstract Animal createAnimal(); } public class DogFactory extends AnimalFactory { public Animal createAnimal() { return new Dog(); } } public class CatFactory extends AnimalFactory { public Animal createAnimal() { return new Cat(); } } public class Main { public static void main(String[] args) { AnimalFactory factory1 = new DogFactory(); Animal animal1 = factory1.createAnimal(); AnimalFactory factory2 = new CatFactory(); Animal animal2 = factory2.createAnimal(); animal1.makeSound(); // Output: Woof! animal2.makeSound(); // Output: Meow! } } ``` 3. 抽象工厂模式 抽象工厂模式是一种提供一个接口来创建一系列相关或相互依赖对象的设计模式。在这种模式中,客户端通过调用工厂接口的方法来创建不同类型的对象。 示例代码: ``` public interface Animal { public void makeSound(); } public class Dog implements Animal { public void makeSound() { System.out.println("Woof!"); } } public class Cat implements Animal { public void makeSound() { System.out.println("Meow!"); } } public interface AnimalFactory { public Animal createAnimal(); } public class DomesticAnimalFactory implements AnimalFactory { public Animal createAnimal() { return new Dog(); } } public class WildAnimalFactory implements AnimalFactory { public Animal createAnimal() { return new Cat(); } } public class Main { public static void main(String[] args) { AnimalFactory factory1 = new DomesticAnimalFactory(); Animal animal1 = factory1.createAnimal(); AnimalFactory factory2 = new WildAnimalFactory(); Animal animal2 = factory2.createAnimal(); animal1.makeSound(); // Output: Woof! animal2.makeSound(); // Output: Meow! } } ``` 4. 单例模式 单例模式是一种保证一个类只有一个实例,并提供全局访问点的设计模式。在这种模式中,构造函数是私有的,只能通过静态方法来获取实例。 示例代码: ``` public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } public class Main { public static void main(String[] args) { Singleton singleton1 = Singleton.getInstance(); Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton1 == singleton2); // Output: true } } ``` 5. 原型模式 原型模式是一种通过复制现有对象来创建新对象的设计模式。在这种模式中,通过调用对象的克隆方法来创建新对象。 示例代码: ``` public class Sheep implements Cloneable { private String name; public Sheep(String name) { this.name = name; } public void setName(String name) { this.name = name; } public String getName() { return name; } public Sheep clone() { try { return (Sheep) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } } public class Main { public static void main(String[] args) { Sheep sheep1 = new Sheep("Dolly"); Sheep sheep2 = sheep1.clone(); sheep2.setName("Molly"); System.out.println(sheep1.getName()); // Output: Dolly System.out.println(sheep2.getName()); // Output: Molly } } ``` 6. 建造者模式 建造者模式是一种将复杂对象的构建过程分离出来的设计模式。在这种模式中,通过调用建造者类的方法来构建对象,可以灵活地定制对象的组成部分。 示例代码: ``` public class Computer { private String cpu; private String gpu; private String memory; private String storage; public Computer(String cpu, String gpu, String memory, String storage) { this.cpu = cpu; this.gpu = gpu; this.memory = memory; this.storage = storage; } public String getCpu() { return cpu; } public String getGpu() { return gpu; } public String getMemory() { return memory; } public String getStorage() { return storage; } } public interface ComputerBuilder { public void setCpu(String cpu); public void setGpu(String gpu); public void setMemory(String memory); public void setStorage(String storage); public Computer build(); } public class GamingComputerBuilder implements ComputerBuilder { private String cpu; private String gpu; private String memory; private String storage; public void setCpu(String cpu) { this.cpu = cpu; } public void setGpu(String gpu) { this.gpu = gpu; } public void setMemory(String memory) { this.memory = memory; } public void setStorage(String storage) { this.storage = storage; } public Computer build() { return new Computer(cpu, gpu, memory, storage); } } public class OfficeComputerBuilder implements ComputerBuilder { private String cpu; private String memory; private String storage; public void setCpu(String cpu) { this.cpu = cpu; } public void setGpu(String gpu) {} public void setMemory(String memory) { this.memory = memory; } public void setStorage(String storage) { this.storage = storage; } public Computer build() { return new Computer(cpu, null, memory, storage); } } public class ComputerDirector { private ComputerBuilder builder; public void setBuilder(ComputerBuilder builder) { this.builder = builder; } public Computer buildComputer() { builder.setCpu("Intel i7"); builder.setMemory("16GB"); builder.setStorage("512GB SSD"); return builder.build(); } } public class Main { public static void main(String[] args) { ComputerDirector director = new ComputerDirector(); ComputerBuilder builder1 = new GamingComputerBuilder(); ComputerBuilder builder2 = new OfficeComputerBuilder(); director.setBuilder(builder1); Computer gamingComputer = director.buildComputer(); director.setBuilder(builder2); Computer officeComputer = director.buildComputer(); System.out.println(gamingComputer.getCpu()); // Output: Intel i7 System.out.println(gamingComputer.getGpu()); // Output: NVIDIA GTX System.out.println(officeComputer.getCpu()); // Output: Intel i7 System.out.println(officeComputer.getGpu()); // Output: null } } ``` 以上是关于六种创建型设计模式的简要介绍和示例代码。希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值