易学设计模式看书笔记(3) - 工厂方法模式

本文深入探讨了工厂方法模式的概念、优点及其在动物管理系统中的应用实例,包括抽象类、具体实现类、工厂接口及其实现,以及客户端如何调用工厂方法模式创建对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


二、工厂方法模式

1.动物管理系统的例子

首先,抽象的动物类和具体的动物实现类:

public interface Animal{

  public void eat();

}

public class Tiger implements Animal
{
	public void eat(){
		sysout.out.println("老虎会吃");
	};
	public void run(){
		sysout.out.println("老虎会跑");
	};
}

public class Dolphin implements Animal
{
	public void eat(){
		sysout.out.println("海豚会吃");
	};
	public void swim(){
		sysout.out.println("海豚会游泳");
	};
}

然后设计一个只负责定义创建方式的抽象工厂类:

public interface Factory
{
	public Animal createAnimail();
}

再分别设计老虎、海豚的具体工厂实现类,都继承抽象工厂类:

public class Trigerfactory implements Factory
{
	public Animal createAnimal(){
		return new Triger();
	}
}

public class Dolphinfactory implements Factory
{
	public Animal createAnimal(){
		return new Dolphin();
	}
}

客户端调用:

public class Client
{
	public static void main(String[] args) 
	{
		Factory factory = new TrierFactory();
		Animal animal = factory.createAnimal();
		animal.eat();
		factory = new DolphinFactory();
		animal = fatory.createAnimal();
		animal.eat();
	}
}

 

2.工厂方法模式简介

  定义:工厂方法模式中抽象工厂负责定义创建对象的接口,
  具体对象的创建工作由实现抽象工厂的具体工厂类来完成。

3.工厂方法模式的优缺点:

优点:

    在工厂方法模式中,客户端不再负责对象的创建,
而是把这个责任交给了具体的工厂类,客户端只负责对象的调用,
明确了各个类的职责。
    如果有新的产品加进来,只需要增加一个具体的创建产品工厂类
和具体的产品类,不会影响其他原有的代码,后期维护更加容易,
增强了系统的可扩展性。

缺点:
   
 需要额外的编写代码,增加了工作量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值