创建型-综合案例

题目

创建型-综合案例

案例名称:智能家居设备控制平台的设备创建模块


背景场景:

在一个智能家居平台中,用户可以通过手机 App 添加多种设备,比如:

  • 智能灯(SmartLight)
  • 智能空调(SmartAirConditioner)
  • 智能音箱(SmartSpeaker)

不同设备厂商(如小米、华为、飞利浦)提供各自设备的实现和初始化方式。平台必须根据用户选择的“设备类型”和“厂商”创建对应的设备对象,并确保:

  • 创建过程灵活扩展,不修改已有代码(工厂方法/抽象工厂
  • 有些核心类只能有一个实例(单例
  • 某些设备初始化非常复杂,如音箱可能包含语音识别模块、Wi-Fi 模块、音效设置等(建造者模式
  • 某些设备创建后要批量复制相似对象,如多个房间部署相同灯具配置(原型模式

涉及的创建型模式

模式名 在此场景中的用途
单例模式 控制平台的“设备中心管理器”只能有一个实例
工厂方法 为每种设备类型定义一个工厂
抽象工厂 根据厂商批量创建不同类型的设备
建造者模式 构建复杂的设备(如智能音箱)
原型模式 快速复制已有设备配置用于部署

案例要求与功能说明

用户通过界面选择设备类型和厂商

例如:

请选择设备类型:[Light, AirConditioner, Speaker]

请选择设备厂商:[Xiaomi, Huawei, Philips]

系统将创建对应厂商的设备对象,例如:

  • XiaomiLight
  • HuaweiAirConditioner
  • PhilipsSpeaker

不同厂商的设备实现细节不同

例如:
- XiaomiLight 需要初始化米家协议
- HuaweiSpeaker 默认语音助手是小艺

部署多个房间的同款设备时,使用原型模式

SmartLight template = new XiaomiLight();
SmartLight light2 = template.clone();
SmartLight light3 = template.clone();


智能音箱设备初始化复杂:通过建造者创建
SpeakerBuilder builder = new HuaweiSpeakerBuilder();
Director director = new Director(builder);
SmartSpeaker speaker = director.construct();


系统中的 DeviceManager 为单例,集中管理设备注册与列表
DeviceManager.getInstance().register(device);


编程练习目标

  1. 使用工厂方法模式为每种设备类型创建工厂(如 LightFactory)
  2. 使用抽象工厂创建“设备族”(如      XiaomiDeviceFactory → 生产小米灯、小米空调等)
  3. 为复杂设备(如 Speaker)实现建造者模式
  4. 实现原型接口,使设备支持快速 clone
  5. 确保 DeviceManager 是线程安全的单例
  6. 提供控制台模拟用户选择厂商/设备并创建的交互界面

技术提示

  • 使用接口 SmartDevice 作为设备抽象父类
  • Light, AirConditioner, Speaker 作为子接口
  • 每种厂商实现各自产品族
  • 使用 Cloneable 实现原型
  • 使用 enum 模拟用户选择

示例输出

欢迎使用智能家居系统

请选择设备类型:[Light]

请选择设备厂商:[Xiaomi]

数据:已创建设备:XiaomiLight(默认亮度80%,支持米家协议)

设备已注册到 DeviceManager

是否部署多个房间?Y

设备克隆成功:Room2 使用 XiaomiLight

设备克隆成功:Room3 使用 XiaomiLight

代码

PlantUML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
@startuml
!theme plain

' 设置全局样式
skinparam class {
BackgroundColor White
ArrowColor Black
BorderColor Black
}
skinparam interface {
BackgroundColor LightBlue
ArrowColor Black
BorderColor Black
}
skinparam abstract {
BackgroundColor LightGray
ArrowColor Black
BorderColor Black
}
skinparam enum {
BackgroundColor LightGreen
ArrowColor Black
BorderColor Black
}

' 枚举
enum DeviceType {
LIGHT
AIR_CONDITIONER
SPEAKER
}

enum Manufacturer {
XIAOMI
HUAWEI
PHILIPS
}

' 单例模式:设备中心管理器
class DeviceManager {
- {static} volatile instance: DeviceManager
- registeredDevices: ConcurrentHashMap<String, SmartDevice>
- deviceCount: int
- DeviceManager()
+ {static} getInstance(): DeviceManager
+ registerDevice(device: SmartDevice): void
+ getAllDevices(): List<SmartDevice>
+ clearDevices(): void
}
note left of DeviceManager
**单例模式**
- 确保只有一个实例
- 双重检查锁定
end note

' 抽象产品接口 (产品家族)
interface SmartDevice {
+ turnOn(): void
+ turnOff(): void
+ displayInfo(): void
}

interface SmartLight {
+ setBrightness(brightness: int): void
+ clone(): SmartLight
}
SmartDevice <|-- SmartLight
Cloneable <|.. SmartLight

interface SmartAirConditioner {
+ setTemperature(temperature: int): void
}
SmartDevice <|-- SmartAirConditioner

interface SmartSpeaker {
+ playMusic(song: String): void
+ setVoiceAssistant(assistant: String): void
+ setWiFiModule(module: String): void
+ setSoundSettings(settings: String): void
}
SmartDevice <|-- SmartSpeaker

' 具体产品实现
class XiaomiLight {
- brightness: int
+ XiaomiLight()
+ turnOn(): void
+ turnOff(): void
+ setBrightness(brightness: int): void
+ displayInfo(): void
+ clone(): SmartLight
}
SmartLight <|.. XiaomiLight

class HuaweiLight {
- brightness: int
+ HuaweiLight()
+ turnOn(): void
+ turnOff(): void
+ setBrightness(brightness: int): void
+ displayInfo(): void
+ clone(): SmartLight
}
SmartLight <|.. HuaweiLight

class PhilipsLight {
- brightness: int
+ PhilipsLight()
+ turnOn(): void
+ turnOff(): void
+ setBrightness(brightness: int): void
+ displayInfo(): void
+ clone(): SmartLight
}
SmartLight <|.. PhilipsLight

class XiaomiAirConditioner {
- temperature: int
+ XiaomiAirConditioner()
+ turnOn(): void
+ turnOff(): void
+ setTemperature(temperature: int): void
+ displayInfo(): void
}
SmartAirConditioner <|.. XiaomiAirConditioner

class HuaweiAirConditioner {
- temperature: int
+ HuaweiAirConditioner()
+ turnOn(): void
+ turnOff(): void
+ setTemperature(temperature: int): void
+ displayInfo(): void
}
SmartAirConditioner <|.. HuaweiAirConditioner

class PhilipsAirConditioner {
- temperature: int
+ PhilipsAirConditioner()
+ turnOn(): void
+ turnOff(): void
+ setTemperature(temperature: int): void
+ displayInfo(): void
}
SmartAirConditioner <|.. PhilipsAirConditioner

class SmartSpeakerImpl {
- voiceAssistant: String
- wiFiModule: String
- soundSettings: String
- dspChip: SpeakerComponent
+ SmartSpeakerImpl()
+ turnOn(): void
+ turnOff(): void
+ playMusic(song: String): void
+ setVoiceAssistant(assistant: String): void
+ setWiFiModule(module: String): void
+ setSoundSettings(settings: String): void
+ setDspChip(dspChip: SpeakerComponent): void
+ displayInfo(): void
}
SmartSpeaker <|.. SmartSpeakerImpl
Serializable <|.. SmartSpeakerImpl

class SpeakerComponent {
- name: String
- version: String
+ SpeakerComponent(name: String, version: String)
+ getName(): String
+ getVersion(): String
+ toString(): String
}
Serializable <|.. SpeakerComponent

SmartSpeakerImpl *-- SpeakerComponent : contains >

' 抽象工厂模式:设备工厂接口
interface DeviceFactory {
+ createLight(): SmartLight
+ createAirConditioner(): SmartAirConditioner
+ createSpeaker(): SmartSpeaker
}

' 具体工厂实现
class XiaomiDeviceFactory {
+ createLight(): SmartLight
+ createAirConditioner(): SmartAirConditioner
+ createSpeaker(): SmartSpeaker
}
DeviceFactory <|.. XiaomiDeviceFactory
XiaomiDeviceFactory ..> XiaomiLight : creates >
XiaomiDeviceFactory ..> XiaomiAirConditioner : creates >
XiaomiDeviceFactory ..> SmartSpeakerImpl : creates (via Builder) >

class HuaweiDeviceFactory {
+ createLight(): SmartLight
+ createAirConditioner(): SmartAirConditioner
+ createSpeaker(): SmartSpeaker
}
DeviceFactory <|.. HuaweiDeviceFactory
HuaweiDeviceFactory ..> HuaweiLight : creates >
HuaweiDeviceFactory ..> HuaweiAirConditioner : creates >
HuaweiDeviceFactory ..> SmartSpeakerImpl : creates (via Builder) >

class PhilipsDeviceFactory {
+ createLight(): SmartLight
+ createAirConditioner(): SmartAirConditioner
+ createSpeaker(): SmartSpeaker
}
DeviceFactory <|.. PhilipsDeviceFactory
PhilipsDeviceFactory ..> PhilipsLight : creates >
PhilipsDeviceFactory ..> PhilipsAirConditioner : creates >
PhilipsDeviceFactory ..> SmartSpeakerImpl : creates (via Builder) >

' 建造者模式:音箱建造者
interface SpeakerBuilder {
+ buildVoiceAssistant(): void
+ buildWiFiModule(): void
+ buildSoundSettings(): void
+ buildDspChip(): void
+ getSpeaker(): SmartSpeaker
}

class XiaomiSpeakerBuilder {
- speaker: SmartSpeakerImpl
+ buildVoiceAssistant(): void
+ buildWiFiModule(): void
+ buildSoundSettings(): void
+ buildDspChip(): void
+ getSpeaker(): SmartSpeaker
}
SpeakerBuilder <|.. XiaomiSpeakerBuilder
XiaomiSpeakerBuilder o-- SmartSpeakerImpl : builds >
XiaomiSpeakerBuilder ..> SpeakerComponent : creates >

class HuaweiSpeakerBuilder {
- speaker: SmartSpeakerImpl
+ buildVoiceAssistant(): void
+ buildWiFiModule(): void
+ buildSoundSettings(): void
+ buildDspChip(): void
+ getSpeaker(): SmartSpeaker
}
SpeakerBuilder <|.. HuaweiSpeakerBuilder
HuaweiSpeakerBuilder o-- SmartSpeakerImpl : builds >
HuaweiSpeakerBuilder ..> SpeakerComponent : creates >

class PhilipsSpeakerBuilder {
- speaker: SmartSpeakerImpl
+ buildVoiceAssistant(): void
+ buildWiFiModule(): void
+ buildSoundSettings(): void
+ buildDspChip(): void
+ getSpeaker(): SmartSpeaker
}
SpeakerBuilder <|.. PhilipsSpeakerBuilder
PhilipsSpeakerBuilder o-- SmartSpeakerImpl : builds >
PhilipsSpeakerBuilder ..> SpeakerComponent : creates >

class SpeakerDirector {
- builder: SpeakerBuilder
+ SpeakerDirector(builder: SpeakerBuilder)
+ construct(): SmartSpeaker
}
SpeakerDirector o-- SpeakerBuilder : directs >

' 客户端
class SmartHomeClient {
+ {static} main(args: String[]): void
}

' 客户端与各模式的交互
SmartHomeClient ..> DeviceManager
SmartHomeClient ..> DeviceFactory
SmartHomeClient ..> SmartDevice
SmartHomeClient ..> SmartLight
SmartHomeClient ..> DeviceType
SmartHomeClient ..> Manufacturer

' 抽象工厂内部使用建造者
XiaomiDeviceFactory ..> XiaomiSpeakerBuilder
XiaomiDeviceFactory ..> SpeakerDirector

HuaweiDeviceFactory ..> HuaweiSpeakerBuilder
HuaweiDeviceFactory ..> SpeakerDirector

PhilipsDeviceFactory ..> PhilipsSpeakerBuilder
PhilipsDeviceFactory ..> SpeakerDirector

@enduml

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap; // 用于线程安全的设备注册

// 案例名称:智能家居设备控制平台的设备创建模块

// 枚举:设备类型
enum DeviceType {
LIGHT, AIR_CONDITIONER, SPEAKER
}

// 枚举:设备厂商
enum Manufacturer {
XIAOMI, HUAWEI, PHILIPS
}

/**
* 智能设备抽象接口 (产品抽象)
*/
interface SmartDevice {
void turnOn();
void turnOff();
void displayInfo();
}

/**
* 智能灯接口 (具体产品抽象)
* 实现 Cloneable 接口,支持原型模式
*/
interface SmartLight extends SmartDevice, Cloneable {
void setBrightness(int brightness);
SmartLight clone() throws CloneNotSupportedException; // 声明克隆方法
}

/**
* 智能空调接口 (具体产品抽象)
*/
interface SmartAirConditioner extends SmartDevice {
void setTemperature(int temperature);
}

/**
* 智能音箱接口 (具体产品抽象)
* 这是一个复杂对象,将通过建造者模式构建
*/
interface SmartSpeaker extends SmartDevice {
void playMusic(String song);
void setVoiceAssistant(String assistant);
void setWiFiModule(String module);
void setSoundSettings(String settings);
}

/**
* 附件类 (用于建造者模式中音箱的复杂部件)
* 实现 Serializable 接口,确保深克隆时能被序列化
*/
class SpeakerComponent implements Serializable {
private String name;
private String version;

public SpeakerComponent(String name, String version) {
this.name = name;
this.version = version;
}

public String getName() {
return name;
}

public String getVersion() {
return version;
}

@Override
public String toString() {
return name + " (v" + version + ")";
}
}

/**
* 单例模式:设备中心管理器
* 负责设备的注册和管理,确保只有一个实例
*/
class DeviceManager {
// 使用 volatile 关键字确保多线程环境下的可见性
private static volatile DeviceManager instance;
// 使用 ConcurrentHashMap 确保线程安全的设备列表
private ConcurrentHashMap<String, SmartDevice> registeredDevices;
private int deviceCount = 0;

// 私有构造函数,防止外部实例化
private DeviceManager() {
registeredDevices = new ConcurrentHashMap<>();
System.out.println("DeviceManager: 设备管理器已初始化(单例)");
}

// 获取单例实例的静态方法 (双重检查锁定,线程安全)
public static DeviceManager getInstance() {
if (instance == null) { // 第一次检查,避免不必要的同步
synchronized (DeviceManager.class) { // 同步块,确保只有一个线程创建实例
if (instance == null) { // 第二次检查,防止多个线程同时通过第一次检查
instance = new DeviceManager();
}
}
}
return instance;
}

// 注册设备
public void registerDevice(SmartDevice device) {
String deviceId = "device-" + (++deviceCount);
registeredDevices.put(deviceId, device);
System.out.println("DeviceManager: 设备 " + device.getClass().getSimpleName() + " 已注册,ID: " + deviceId);
}

// 获取所有注册设备
public List<SmartDevice> getAllDevices() {
return new ArrayList<>(registeredDevices.values());
}

// 清空所有设备 (仅用于测试或特定管理场景)
public void clearDevices() {
registeredDevices.clear();
deviceCount = 0;
System.out.println("DeviceManager: 所有设备已清空。");
}
}

/**
* 抽象工厂模式:设备工厂接口 (Abstract Factory)
* 定义了创建不同类型设备的方法
*/
interface DeviceFactory {
SmartLight createLight();
SmartAirConditioner createAirConditioner();
SmartSpeaker createSpeaker();
}

// ------------------- 具体产品实现 -------------------

/**
* 小米智能灯 (具体产品)
* 实现 SmartLight 接口和 Cloneable 接口
*/
class XiaomiLight implements SmartLight {
private int brightness;

public XiaomiLight() {
this.brightness = 80; // 默认亮度
System.out.println("XiaomiLight: 初始化小米智能灯(默认亮度" + brightness + "%,支持米家协议)");
}

@Override
public void turnOn() {
System.out.println("XiaomiLight: 灯已开启,亮度 " + brightness + "%");
}

@Override
public void turnOff() {
System.out.println("XiaomiLight: 灯已关闭");
}

@Override
public void setBrightness(int brightness) {
this.brightness = brightness;
System.out.println("XiaomiLight: 亮度设置为 " + brightness + "%");
}

@Override
public void displayInfo() {
System.out.println("XiaomiLight: 亮度 " + brightness + "%,支持米家协议");
}

// 原型模式:实现浅克隆 (对于简单字段,浅克隆即深克隆)
@Override
public SmartLight clone() throws CloneNotSupportedException {
// 对于只包含基本类型和String的类,浅克隆通常足够。
// 如果包含复杂对象,需要手动实现深克隆或利用序列化。
System.out.println("XiaomiLight: 正在克隆小米智能灯...");
return (SmartLight) super.clone();
}
}

/**
* 华为智能灯 (具体产品)
*/
class HuaweiLight implements SmartLight {
private int brightness;

public HuaweiLight() {
this.brightness = 70;
System.out.println("HuaweiLight: 初始化华为智能灯(默认亮度" + brightness + "%,支持鸿蒙智联)");
}

@Override
public void turnOn() {
System.out.println("HuaweiLight: 灯已开启,亮度 " + brightness + "%");
}

@Override
public void turnOff() {
System.out.println("HuaweiLight: 灯已关闭");
}

@Override
public void setBrightness(int brightness) {
this.brightness = brightness;
System.out.println("HuaweiLight: 亮度设置为 " + brightness + "%");
}

@Override
public void displayInfo() {
System.out.println("HuaweiLight: 亮度 " + brightness + "%,支持鸿蒙智联");
}

@Override
public SmartLight clone() throws CloneNotSupportedException {
System.out.println("HuaweiLight: 正在克隆华为智能灯...");
return (SmartLight) super.clone();
}
}

/**
* 飞利浦智能灯 (具体产品)
*/
class PhilipsLight implements SmartLight {
private int brightness;

public PhilipsLight() {
this.brightness = 90;
System.out.println("PhilipsLight: 初始化飞利浦智能灯(默认亮度" + brightness + "%,支持Hue生态)");
}

@Override
public void turnOn() {
System.out.println("PhilipsLight: 灯已开启,亮度 " + brightness + "%");
}

@Override
public void turnOff() {
System.out.println("PhilipsLight: 灯已关闭");
}

@Override
public void setBrightness(int brightness) {
this.brightness = brightness;
System.out.println("PhilipsLight: 亮度设置为 " + brightness + "%");
}

@Override
public void displayInfo() {
System.out.println("PhilipsLight: 亮度 " + brightness + "%,支持Hue生态");
}

@Override
public SmartLight clone() throws CloneNotSupportedException {
System.out.println("PhilipsLight: 正在克隆飞利浦智能灯...");
return (SmartLight) super.clone();
}
}

/**
* 小米智能空调 (具体产品)
*/
class XiaomiAirConditioner implements SmartAirConditioner {
private int temperature;

public XiaomiAirConditioner() {
this.temperature = 26;
System.out.println("XiaomiAirConditioner: 初始化小米智能空调(默认温度" + temperature + "℃)");
}

@Override
public void turnOn() {
System.out.println("XiaomiAirConditioner: 空调已开启,当前温度 " + temperature + "℃");
}

@Override
public void turnOff() {
System.out.println("XiaomiAirConditioner: 空调已关闭");
}

@Override
public void setTemperature(int temperature) {
this.temperature = temperature;
System.out.println("XiaomiAirConditioner: 温度设置为 " + temperature + "℃");
}

@Override
public void displayInfo() {
System.out.println("XiaomiAirConditioner: 当前温度 " + temperature + "℃");
}
}

/**
* 华为智能空调 (具体产品)
*/
class HuaweiAirConditioner implements SmartAirConditioner {
private int temperature;

public HuaweiAirConditioner() {
this.temperature = 25;
System.out.println("HuaweiAirConditioner: 初始化华为智能空调(默认温度" + temperature + "℃)");
}

@Override
public void turnOn() {
System.out.println("HuaweiAirConditioner: 空调已开启,当前温度 " + temperature + "℃");
}

@Override
public void turnOff() {
System.out.println("HuaweiAirConditioner: 空调已关闭");
}

@Override
public void setTemperature(int temperature) {
this.temperature = temperature;
System.out.println("HuaweiAirConditioner: 温度设置为 " + temperature + "℃");
}

@Override
public void displayInfo() {
System.out.println("HuaweiAirConditioner: 当前温度 " + temperature + "℃");
}
}

/**
* 飞利浦智能空调 (具体产品)
*/
class PhilipsAirConditioner implements SmartAirConditioner {
private int temperature;

public PhilipsAirConditioner() {
this.temperature = 24;
System.out.println("PhilipsAirConditioner: 初始化飞利浦智能空调(默认温度" + temperature + "℃)");
}

@Override
public void turnOn() {
System.out.println("PhilipsAirConditioner: 空调已开启,当前温度 " + temperature + "℃");
}

@Override
public void turnOff() {
System.out.println("PhilipsAirConditioner: 空调已关闭");
}

@Override
public void setTemperature(int temperature) {
this.temperature = temperature;
System.out.println("PhilipsAirConditioner: 温度设置为 " + temperature + "℃");
}

@Override
public void displayInfo() {
System.out.println("PhilipsAirConditioner: 当前温度 " + temperature + "℃");
}
}

/**
* 智能音箱具体实现 (产品类,由建造者模式构建)
*/
class SmartSpeakerImpl implements SmartSpeaker, Serializable { // 同样需要序列化以便深克隆
private String voiceAssistant;
private String wiFiModule;
private String soundSettings;
private SpeakerComponent dspChip; // 复杂部件

public SmartSpeakerImpl() {
System.out.println("SmartSpeakerImpl: 正在组装智能音箱...");
}

@Override
public void turnOn() {
System.out.println("SmartSpeakerImpl: 音箱已开启");
}

@Override
public void turnOff() {
System.out.println("SmartSpeakerImpl: 音箱已关闭");
}

@Override
public void playMusic(String song) {
System.out.println("SmartSpeakerImpl: 正在播放 " + song);
}

@Override
public void setVoiceAssistant(String assistant) {
this.voiceAssistant = assistant;
}

@Override
public void setWiFiModule(String module) {
this.wiFiModule = module;
}

@Override
public void setSoundSettings(String settings) {
this.soundSettings = settings;
}

public void setDspChip(SpeakerComponent dspChip) {
this.dspChip = dspChip;
}

@Override
public void displayInfo() {
System.out.println("SmartSpeakerImpl 配置:");
System.out.println(" 语音助手: " + voiceAssistant);
System.out.println(" Wi-Fi 模块: " + wiFiModule);
System.out.println(" 音效设置: " + soundSettings);
if (dspChip != null) {
System.out.println(" DSP 芯片: " + dspChip);
}
}
}

// ------------------- 建造者模式实现 -------------------

/**
* 抽象建造者:音箱建造者 (Abstract Builder)
*/
interface SpeakerBuilder {
void buildVoiceAssistant();
void buildWiFiModule();
void buildSoundSettings();
void buildDspChip(); // 构建复杂部件
SmartSpeaker getSpeaker();
}

/**
* 小米音箱建造者 (Concrete Builder)
*/
class XiaomiSpeakerBuilder implements SpeakerBuilder {
private SmartSpeakerImpl speaker = new SmartSpeakerImpl();

@Override
public void buildVoiceAssistant() {
speaker.setVoiceAssistant("小爱同学");
}

@Override
public void buildWiFiModule() {
speaker.setWiFiModule("Wi-Fi 5 (802.11ac)");
}

@Override
public void buildSoundSettings() {
speaker.setSoundSettings("小米澎湃音效");
}

@Override
public void buildDspChip() {
speaker.setDspChip(new SpeakerComponent("Xiaomi DSP", "v1.0"));
}

@Override
public SmartSpeaker getSpeaker() {
return speaker;
}
}

/**
* 华为音箱建造者 (Concrete Builder)
*/
class HuaweiSpeakerBuilder implements SpeakerBuilder {
private SmartSpeakerImpl speaker = new SmartSpeakerImpl();

@Override
public void buildVoiceAssistant() {
speaker.setVoiceAssistant("小艺");
}

@Override
public void buildWiFiModule() {
speaker.setWiFiModule("Wi-Fi 6 (802.11ax)");
}

@Override
public void buildSoundSettings() {
speaker.setSoundSettings("华为Histen音效");
}

@Override
public void buildDspChip() {
speaker.setDspChip(new SpeakerComponent("Huawei HiSilicon", "v2.0"));
}

@Override
public SmartSpeaker getSpeaker() {
return speaker;
}
}

/**
* 飞利浦音箱建造者 (Concrete Builder)
*/
class PhilipsSpeakerBuilder implements SpeakerBuilder {
private SmartSpeakerImpl speaker = new SmartSpeakerImpl();

@Override
public void buildVoiceAssistant() {
speaker.setVoiceAssistant("Google Assistant");
}

@Override
public void buildWiFiModule() {
speaker.setWiFiModule("Wi-Fi 5 (802.11ac)");
}

@Override
public void buildSoundSettings() {
speaker.setSoundSettings("Philips Fidelio 音效");
}

@Override
public void buildDspChip() {
speaker.setDspChip(new SpeakerComponent("Philips Audio Engine", "v1.5"));
}

@Override
public SmartSpeaker getSpeaker() {
return speaker;
}
}

/**
* 指挥者:音箱建造指挥者 (Director)
*/
class SpeakerDirector {
private SpeakerBuilder builder;

public SpeakerDirector(SpeakerBuilder builder) {
this.builder = builder;
}

public SmartSpeaker construct() {
builder.buildVoiceAssistant();
builder.buildWiFiModule();
builder.buildSoundSettings();
builder.buildDspChip(); // 构建复杂部件
return builder.getSpeaker();
}
}

// ------------------- 抽象工厂具体实现 -------------------

/**
* 小米设备工厂 (Concrete Abstract Factory)
*/
class XiaomiDeviceFactory implements DeviceFactory {
@Override
public SmartLight createLight() {
return new XiaomiLight();
}

@Override
public SmartAirConditioner createAirConditioner() {
return new XiaomiAirConditioner();
}

@Override
public SmartSpeaker createSpeaker() {
// 使用建造者模式创建复杂音箱
SpeakerBuilder builder = new XiaomiSpeakerBuilder();
SpeakerDirector director = new SpeakerDirector(builder);
return director.construct();
}
}

/**
* 华为设备工厂 (Concrete Abstract Factory)
*/
class HuaweiDeviceFactory implements DeviceFactory {
@Override
public SmartLight createLight() {
return new HuaweiLight();
}

@Override
public SmartAirConditioner createAirConditioner() {
return new HuaweiAirConditioner();
}

@Override
public SmartSpeaker createSpeaker() {
// 使用建造者模式创建复杂音箱
SpeakerBuilder builder = new HuaweiSpeakerBuilder();
SpeakerDirector director = new SpeakerDirector(builder);
return director.construct();
}
}

/**
* 飞利浦设备工厂 (Concrete Abstract Factory)
*/
class PhilipsDeviceFactory implements DeviceFactory {
@Override
public SmartLight createLight() {
return new PhilipsLight();
}

@Override
public SmartAirConditioner createAirConditioner() {
return new PhilipsAirConditioner();
}

@Override
public SmartSpeaker createSpeaker() {
// 使用建造者模式创建复杂音箱
SpeakerBuilder builder = new PhilipsSpeakerBuilder();
SpeakerDirector director = new SpeakerDirector(builder);
return director.construct();
}
}

/**
* 客户端:模拟用户交互和设备创建
*/
public class SmartHomeClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DeviceManager deviceManager = DeviceManager.getInstance(); // 获取单例设备管理器

System.out.println("欢迎使用智能家居系统");

while (true) {
System.out.println("\n请选择设备类型:[LIGHT, AIR_CONDITIONER, SPEAKER] (输入 'EXIT' 退出)");
String deviceTypeInput = scanner.nextLine().toUpperCase();

if (deviceTypeInput.equals("EXIT")) {
System.out.println("感谢使用,再见!");
break;
}

DeviceType selectedDeviceType;
try {
selectedDeviceType = DeviceType.valueOf(deviceTypeInput);
} catch (IllegalArgumentException e) {
System.out.println("无效的设备类型,请重新输入。");
continue;
}

System.out.println("请选择设备厂商:[XIAOMI, HUAWEI, PHILIPS]");
String manufacturerInput = scanner.nextLine().toUpperCase();

Manufacturer selectedManufacturer;
try {
selectedManufacturer = Manufacturer.valueOf(manufacturerInput);
} catch (IllegalArgumentException e) {
System.out.println("无效的设备厂商,请重新输入。");
continue;
}

DeviceFactory factory = null;
switch (selectedManufacturer) {
case XIAOMI:
factory = new XiaomiDeviceFactory();
break;
case HUAWEI:
factory = new HuaweiDeviceFactory();
break;
case PHILIPS:
factory = new PhilipsDeviceFactory();
break;
}

SmartDevice device = null;
if (factory != null) {
switch (selectedDeviceType) {
case LIGHT:
device = factory.createLight();
break;
case AIR_CONDITIONER:
device = factory.createAirConditioner();
break;
case SPEAKER:
device = factory.createSpeaker();
break;
}
}

if (device != null) {
System.out.println("\n数据:已创建设备:" + device.getClass().getSimpleName());
device.displayInfo();
deviceManager.registerDevice(device); // 注册设备到管理器

// 演示原型模式:如果创建的是智能灯,则提供克隆选项
if (device instanceof SmartLight) {
System.out.println("是否部署多个房间的同款灯具?(Y/N)");
String cloneChoice = scanner.nextLine().toUpperCase();
if (cloneChoice.equals("Y")) {
try {
SmartLight originalLight = (SmartLight) device;
SmartLight clonedLight2 = originalLight.clone();
System.out.println("设备克隆成功:Room2 使用 " + clonedLight2.getClass().getSimpleName());
clonedLight2.setBrightness(60); // 修改克隆体的属性,不影响原件
clonedLight2.displayInfo();
deviceManager.registerDevice(clonedLight2);

SmartLight clonedLight3 = originalLight.clone();
System.out.println("设备克隆成功:Room3 使用 " + clonedLight3.getClass().getSimpleName());
clonedLight3.setBrightness(50); // 再次修改克隆体的属性
clonedLight3.displayInfo();
deviceManager.registerDevice(clonedLight3);

System.out.println("\n原始灯具信息(未受克隆体修改影响):");
originalLight.displayInfo(); // 验证原始灯具未受影响
} catch (CloneNotSupportedException e) {
System.err.println("克隆失败: " + e.getMessage());
}
}
}
} else {
System.out.println("设备创建失败,请检查您的选择。");
}
}
scanner.close();
}
}