今天学习并练习了抽象工厂模式,来个简单的记录。
1.概念:
提供一个创建一系列(相互依赖)对象的接口,而无需指定他们具体的类。
2.具体实例:
Lenovo,Apple两家笔记本电脑制造商扩大生产,增加了手机和电视两种产品,并分出不同 的子厂,试用抽象工厂模式实现。
uml类图:
具体实现代码:
Laptop:
public interface Laptop {
public int getid();
public void printInfo();
}
LenovoLaptop:
public class LenovoLaptop implements Laptop {
private static int id=1000;
String mark = "联想笔记本";
public LenovoLaptop(){
id++;
}
public int getid() {
// TODO 自动生成的方法存根
return id;
}
public void printInfo() {
System.out.println("生产了一台"+mark+",编号为:"+getid());
}
}
AppleLaptop:
public class AppleLaptop implements Laptop {
private static int id=1000;
String mark;
public AppleLaptop(){
mark="Apple笔记本";
id++;
}
public int getid(){
return id;
}
public void printInfo() {
System.out.println("生产了一台"+mark+",编号为:"+getid());
}
}
Phone:
public interface Phone {
String mark = null;
public int getid();
public void printInfo();
}
LenovoPhone:
public class LenovoPhone implements Phone {
private static int id=2000;
String mark;
public LenovoPhone(){
mark="联想手机";
id++;
}
public int getid(){
return id;
}
public void printInfo() {
System.out.println("生产了一台"+mark+",编号为:"+getid());
}
}
ApplePhone:
public class ApplePhone implements Phone {
private static int id=2000;
String mark;
public ApplePhone(){
mark="Apple手机";
id++;
}
public int getid(){
return id;
}
public void printInfo() {
System.out.println("生产了一台"+mark+",编号为:"+getid());
}
}
Tv:
public interface Tv {
String mark = null;
public int getid();
public default void printInfo() {
System.out.println("生产一台"+mark+"牌的电视,编号是"+getid());
}
}
LenovoTv:
public class LenovoTv implements Tv {
private static int id=3000;
String mark;
public LenovoTv(){
mark="联想电视";
id++;
}
public int getid(){
return id;
}
public void printInfo() {
System.out.println("生产了一台"+mark+",编号为:"+getid());
}
}
AppleTv:
public class AppleTv implements Tv {
private static int id=3000;
String mark;
public AppleTv(){
mark="Apple电视";
id++;
}
public int getid(){
return id;
}
public void printInfo() {
System.out.println("生产了一台"+mark+",编号为:"+getid());
}
}
Factory:
public interface Factory {
public Laptop produceLaptop();
public Phone ProducePhone();
public Tv ProduceTv();
}
LenovoFactory:
public class LenovoFactory implements Factory {
public Laptop produceLaptop(){
return new LenovoLaptop();
}
public Phone ProducePhone(){
return new LenovoPhone();
}
public Tv ProduceTv(){
return new LenovoTv();
}
}
AppleFactory:
public class AppleFactory implements Factory {
public Laptop produceLaptop(){
return new AppleLaptop();
}
public Phone ProducePhone(){
return new ApplePhone();
}
public Tv ProduceTv(){
return new AppleTv();
}
}
Shop:
public class shop {
public void getSuit(Factory f) {
f.produceLaptop().printInfo();
f.ProducePhone().printInfo();
f.ProduceTv().printInfo();
}
}
Applation:
public class Applation {
public static void main(String[] args) {
shop shop=new shop();
Factory f=new LenovoFactory();
Factory a=new AppleFactory();
shop.getSuit(f);
shop.getSuit(a);
shop.getSuit(f);
}
}
3.结果如下:
这样可以间接的创建出对象,实现了低耦合的原则。