java使用简单工厂模式改写实验十五: (1)让防盗门类组合锁和摄像头两个接口(2)定义锁和摄像头两个接口的实现类 (3)提供两个工厂类分别负责生成锁和摄像头的实例对象(4)在主类中创建防盗门对象并调用相关方法
时间: 2024-03-02 13:54:34 浏览: 68
好的,我来回答你的问题。
针对你的需求,我们可以使用简单工厂模式来改写实验十五。具体实现如下:
1. 创建防盗门类,并组合锁和摄像头两个接口:
```java
public class SecurityDoor {
private Lock lock;
private Camera camera;
public SecurityDoor(Lock lock, Camera camera) {
this.lock = lock;
this.camera = camera;
}
public void openDoor() {
System.out.println("打开防盗门");
lock.unlock();
camera.open();
}
public void closeDoor() {
System.out.println("关闭防盗门");
lock.lock();
camera.close();
}
}
```
2. 定义锁和摄像头两个接口的实现类:
```java
public interface Lock {
void lock();
void unlock();
}
public interface Camera {
void open();
void close();
}
public class PasswordLock implements Lock {
@Override
public void lock() {
System.out.println("密码锁上锁");
}
@Override
public void unlock() {
System.out.println("密码锁解锁");
}
}
public class FingerprintLock implements Lock {
@Override
public void lock() {
System.out.println("指纹锁上锁");
}
@Override
public void unlock() {
System.out.println("指纹锁解锁");
}
}
public class NormalCamera implements Camera {
@Override
public void open() {
System.out.println("打开普通摄像头");
}
@Override
public void close() {
System.out.println("关闭普通摄像头");
}
}
public class InfraredCamera implements Camera {
@Override
public void open() {
System.out.println("打开红外摄像头");
}
@Override
public void close() {
System.out.println("关闭红外摄像头");
}
}
```
3. 提供两个工厂类分别负责生成锁和摄像头的实例对象:
```java
public class LockFactory {
public static Lock createLock(String type) {
switch (type) {
case "password":
return new PasswordLock();
case "fingerprint":
return new FingerprintLock();
default:
throw new IllegalArgumentException("Invalid type: " + type);
}
}
}
public class CameraFactory {
public static Camera createCamera(String type) {
switch (type) {
case "normal":
return new NormalCamera();
case "infrared":
return new InfraredCamera();
default:
throw new IllegalArgumentException("Invalid type: " + type);
}
}
}
```
4. 在主类中创建防盗门对象并调用相关方法:
```java
public class Main {
public static void main(String[] args) {
Lock passwordLock = LockFactory.createLock("password");
Camera infraredCamera = CameraFactory.createCamera("infrared");
SecurityDoor door = new SecurityDoor(passwordLock, infraredCamera);
door.openDoor();
door.closeDoor();
}
}
```
以上就是使用简单工厂模式改写实验十五的全部内容。希望可以帮到你。
阅读全文