自行设计实验,编写一个工厂设计模式的程序
要求:
其中实体类至少有1个父类,2个子类
父类中有属性、构造方法、普通方法
子类中有自己的属性、构造方法,并重写父类方法
体现面向对象的三大特性 封装、继承、多态
提交格式:
实体类代码:
//包括父类和子类
工厂类代码:
测试类代码:
【以下回答由 GPT 生成】
要实现Java工厂设计模式,需要先确定使用哪种工厂设计模式,包括简单工厂模式、工厂方法模式和抽象工厂模式。不同的设计模式有不同的实现方式。
如果我们选择简单工厂模式,可以按照以下步骤实现:
以下是简单工厂模式的示例代码:
// 产品接口
interface Product {
void use();
}
// 具体产品类A
class ConcreteProductA implements Product {
@Override
public void use() {
System.out.println("使用产品A");
}
}
// 具体产品类B
class ConcreteProductB implements Product {
@Override
public void use() {
System.out.println("使用产品B");
}
}
// 工厂类
class Factory {
public static Product createProduct(String type) {
if (type.equalsIgnoreCase("A")) {
return new ConcreteProductA();
} else if (type.equalsIgnoreCase("B")) {
return new ConcreteProductB();
} else {
throw new IllegalArgumentException("无法创建该类型的产品");
}
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
// 创建产品A
Product productA = Factory.createProduct("A");
productA.use(); // 输出 "使用产品A"
// 创建产品B
Product productB = Factory.createProduct("B");
productB.use(); // 输出 "使用产品B"
}
}
根据你的描述,我们需要设计一个实现工厂设计模式的程序,其中需要包括至少一个父类和两个子类。
在设计实体类、父类和子类时需要考虑以下几点:
以下是一个示例代码,说明了如何设计父类和子类:
// 父类
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + "正在吃饭");
}
}
// 子类 Dog
class Dog extends Animal {
private String color;
public Dog(String name, String color) {
super(name);
this.color = color;
}
@Override
public void eat() {
System.out.println(getName() + "是一只" + color + "的狗,正在吃骨头");
}
public void bark() {
System.out.println(getName() + "正在汪汪叫");
}
}
// 子类 Cat
class Cat extends Animal {
private int age;
public Cat(String name, int age) {
super(name);
this.age = age;
}
@Override
public void eat() {
System.out.println(getName() + "正在吃鱼");
}
public void sleep() {
System.out.println(getName() + "正在睡觉");
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog("旺财", "黄色");
Animal animal2 = new Cat("小花", 3);
animal1.eat(); // 输出 "旺财是一只黄色的狗,正在吃骨头"
animal2.eat(); // 输出 "小花正在吃鱼"
((Dog) animal1).bark(); // 输出 "旺财正在汪汪叫"
((Cat) animal2).sleep(); // 输出 "小花正在睡觉"
}
}
在这个例子中,Animal 类是父类,它包含一个 name 属性和一个 eat() 方法。Dog 类和 Cat 类是 Animal 类的子类,它们分别有自己独特的属性和方法,并且重写了父类的 eat() 方法。通过向上转型和向下转型,我们可以实现多态性,并使用子类特有的方法。
【相关推荐】