类图解析: 通过抽象类的方式建立抽象产品类Phone,并声明抽象方法producePhone 通过抽象类的方式建立抽象产品类NoteBook,并声明抽象方法produceNoteBook 通过接口的方式建立抽象工厂Facto
类图解析:
代码如下:
//Phone抽象类,可以用接口方式代替public abstract class Phone {
abstract void producePhone();
}
//NoteBook抽象类,可以用接口方式代替
public abstract class NoteBook {
abstract void produceNoteBook();
}
//抽象工厂
public interface Factory {
Phone getPhone();
NoteBook getNoteBook();
}
//Apple Phone类
public class ApplePhone extends Phone {
@Override
void producePhone() {
System.out.println("生产苹果手机");
}
}
//Apple MacBook类
public class AppleMacBook extends NoteBook {
@Override
void produceNoteBook() {
System.out.println("生产苹果MacBook");
}
}
//Apple工厂类
public class AppleFactory implements Factory {
@Override
public Phone getPhone() {
return new ApplePhone();
}
@Override
public NoteBook getNoteBook() {
return new AppleMacBook();
}
}
//Huawei Phone类
public class HuaweiPhone extends Phone {
@Override
void producePhone() {
System.out.println("生产华为手机");
}
}
//Huawei NoteBook类
public class HuaweiNoteBook extends NoteBook {
@Override
void produceNoteBook() {
System.out.println("生产华为笔记本电脑");
}
}
//Huawei工厂类
public class HuaweiFactory implements Factory {
@Override
public Phone getPhone() {
return new HuaweiPhone();
}
@Override
public NoteBook getNoteBook() {
return new HuaweiNoteBook();
}
}
//测试类
public class Test {
public static void main(String[] args) {
Factory appleFactory = new AppleFactory();
appleFactory.getPhone().producePhone();
appleFactory.getNoteBook().produceNoteBook();
Factory huaweiFactory = new HuaweiFactory();
huaweiFactory.getPhone().producePhone();
huaweiFactory.getNoteBook().produceNoteBook();
}
}
总结: