详解。。。设计模式2——工厂。。。studying

本文通过具体实例介绍了工厂模式在Java中的应用。重点讲解了如何通过工厂类选择不同的实现类,并通过接口提供给客户端,实现了面向接口编程的目标。

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

设计模式2——工厂

★ 场景和问题

Java程序开发讲究面向接口编程,隐藏具体的实现类,可是如何得到接口呢?

工厂类的命名规范:***Factory
单例工厂方法的命名规范:getInstance()

工厂的本质是“选择实现”

工厂、接口和实现类之间的技术边界:工厂只负责选择实现,实现类才做真正的实现,

而接口是限定到底实现什么东西和返回什么东西,三者之间分工明确、各负其责。


java代码实现:

package cn.hncu.patterns.exercise.factory;

import cn.hncu.patterns.exercise.factory.inter.A;
import cn.hncu.patterns.exercise.factory.model.AFactory;

/*
 * 工厂实现测试:
 * 验证工厂方法是选择实现,
 * 接口指定功能,
 * 实现类实现功能,
 * 工厂选择实现类,
 * 为客户提供不同的功能,
 * 也就是返回不同的接口。
 * 目的:
 * 工厂选择功能。
 * 实现类隐藏。
 * 接口给客户。
 */
public class Client {
	public static void main(String[] args) {
		A a1 = AFactory.createA1();
		A a2 = AFactory.createA2();
		A a3 = AFactory.createA3();
		a1.t1();// 输出1111111111111
		a2.t1();// 输出2222222222222
		a3.t1();// 输出33333
	}

}

package cn.hncu.patterns.exercise.factory.model;

import cn.hncu.patterns.exercise.factory.imp.ImpA1;
import cn.hncu.patterns.exercise.factory.imp.ImpA2;
import cn.hncu.patterns.exercise.factory.imp.ImpA3;
import cn.hncu.patterns.exercise.factory.inter.A;

public class AFactory {
	public AFactory() {
	}

	/*
	 * 使用类反射,
	 * 就可以把下列三个函数合并成一个函数
	 */
	public static A createA1() {
		A a = new ImpA1();
		return a;
	}

	public static A createA2() {
		A a = new ImpA2();
		return a;
	}

	public static A createA3() {
		A a = new ImpA3();
		return a;
	}

}

package cn.hncu.patterns.exercise.factory.inter;

public interface A {
	public abstract void t1();
}

package cn.hncu.patterns.exercise.factory.imp;

import cn.hncu.patterns.exercise.factory.inter.A;

public class ImpA1 implements A {

	@Override
	public void t1() {
		System.out.println("1111111111111");
	}

}

package cn.hncu.patterns.exercise.factory.imp;

import cn.hncu.patterns.exercise.factory.inter.A;

public class ImpA2 implements A {

	@Override
	public void t1() {
		System.out.println("2222222222222");
	}

}

package cn.hncu.patterns.exercise.factory.imp;

import cn.hncu.patterns.exercise.factory.inter.A;

public class ImpA3 implements A {

	@Override
	public void t1() {
		System.out.println("33333");
	}

}








### 使用设计模式表示人类、教师、学生关系 在面向对象的设计中,可以利用设计模式来清晰地表达人类、教师和学生的层次关系及其功能扩展。以下是具体的应用: #### 结构型模式——类适配器模式 如果需要将现有的 `Human` 类的功能扩展到特定的角色(如 `Teacher` 和 `Student`),可以通过 **类适配器模式** 实现继承机制[^1]。这种方式允许子类通过继承父类并覆盖或新增方法实现更具体的逻辑。 ```python class Human: def __init__(self, name): self.name = name def speak(self): return f"{self.name} is speaking." class Teacher(Human): # 继承自 Human def teach(self): return f"{self.name} is teaching." class Student(Human): # 继承自 Human def study(self): return f"{self.name} is studying." ``` 这种设计体现了结构型模式的核心理念:通过组合或继承构建更大规模的对象体系[^1]。 --- #### 行为型模式——策略模式 当需要定义不同的教学风格或者学习方式时,可以引入 **策略模式** 来动态切换行为[^3]。例如,不同类型的老师可能有不同的授课方式,而学生也可能有多种学习习惯。 ```python from abc import ABC, abstractmethod # 定义接口 class TeachingStrategy(ABC): @abstractmethod def teach_method(self): pass class LectureTeaching(TeachingStrategy): def teach_method(self): return "Lecture-based teaching" class InteractiveTeaching(TeachingStrategy): def teach_method(self): return "Interactive learning activities" class TeacherWithStrategy(Human): def __init__(self, name, strategy: TeachingStrategy): super().__init__(name) self.strategy = strategy def set_strategy(self, strategy: TeachingStrategy): self.strategy = strategy def teach_with_strategy(self): return f"{self.name} teaches using {self.strategy.teach_method()} method." teacher = TeacherWithStrategy("Mr. Smith", LectureTeaching()) print(teacher.teach_with_strategy()) # 输出 Mr. Smith teaches using Lecture-based teaching method. teacher.set_strategy(InteractiveTeaching()) print(teacher.teach_with_strategy()) # 输出 Mr. Smith teaches using Interactive learning activities method. ``` 这里展示了如何通过策略模式灵活调整老师的教学方式。 --- #### 创建型模式——工厂方法模式 为了统一管理 `Human` 的实例化过程,尤其是针对不同类型的人群(如教师和学生),可以采用 **工厂方法模式**[^1]。这样能够隐藏复杂的创建逻辑,并提供一致的 API 接口。 ```python class HumanFactory: @staticmethod def create_human(human_type, name): if human_type == 'teacher': return Teacher(name) elif human_type == 'student': return Student(name) raise ValueError(f"Unknown type: {human_type}") # 工厂调用示例 teacher_instance = HumanFactory.create_human('teacher', 'Ms. Brown') student_instance = HumanFactory.create_human('student', 'Alice') print(teacher_instance.speak(), teacher_instance.teach()) # Ms. Brown is speaking. Ms. Brown is teaching. print(student_instance.speak(), student_instance.study()) # Alice is speaking. Alice is studying. ``` 这种方法不仅提高了代码的可维护性,还便于后续扩展新的角色类型[^1]。 --- #### UML 类图展示 根据以上描述,可以用 UML 类图直观展现这些类之间的关系[^2]。假设我们绘制如下结构: - `Human` 是基类; - `Teacher` 和 `Student` 都继承自 `Human`; - `TeachingStrategy` 提供了一个抽象接口,由具体策略类实现其细节。 UML 图形化的表现形式有助于团队成员快速理解系统架构。 --- ### 总结 通过对人类、教师和学生的关系建模,可以看到设计模式的强大之处在于它能有效解决复杂场景下的需求变化问题。无论是通过继承支持多态特性还是借助策略模式增强灵活性,都展现了良好的软件工程实践[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值