最近在学习设计模式,首先在工厂模式中,遇到了抽象工厂模式,所以自己设计了个例子,大概说明了下道理,代码如下:
package abstractfactory;
abstract class MakecarFactory
{
abstract BMW createBMW();
abstract Linken createLinken();
}
abstract class BMW
{
abstract public void printbmw();
}
abstract class Linken
{
abstract public void printLinken();
}
class AsiaBmw extends BMW
{
public void printbmw()
{
System.out.println("我是亚洲的bmw");
}
}
class AsiaLinken extends Linken
{
public void printLinken()
{
System.out.println("我是亚洲的林肯");
}
}
class EuropeBmw extends BMW
{
public void printbmw()
{
System.out.println("我是欧洲的bmw");
}
}
class EuropeLinken extends Linken
{
public void printLinken()
{
System.out.println("我是欧洲的林肯");
}
}
class Asiacar extends MakecarFactory
{
public BMW createBMW()
{
return new AsiaBmw();
}
public Linken createLinken()
{
return new AsiaLinken();
}
}
class Europe extends MakecarFactory
{
public BMW createBMW()
{
return new EuropeBmw();
}
public Linken createLinken()
{
return new EuropeLinken();
}
}
class Test
{
private BMW bmw;
private Linken linken;
public Test(MakecarFactory factory)
{
bmw=factory.createBMW();
linken=factory.createLinken();
}
public void printsomething()
{
bmw.printbmw();
linken.printLinken();
}
}
public class CarFactory
{
public static void main(String[] args)
{
MakecarFactory asiacar=new Asiacar();
Test testcar=new Test(asiacar);
testcar.printsomething();
MakecarFactory europcar=new Europe();
testcar=new Test(europcar);
testcar.printsomething();
}
}
package abstractfactory;
abstract class MakecarFactory
{
abstract BMW createBMW();
abstract Linken createLinken();
}
abstract class BMW
{
abstract public void printbmw();
}
abstract class Linken
{
abstract public void printLinken();
}
class AsiaBmw extends BMW
{
public void printbmw()
{
System.out.println("我是亚洲的bmw");
}
}
class AsiaLinken extends Linken
{
public void printLinken()
{
System.out.println("我是亚洲的林肯");
}
}
class EuropeBmw extends BMW
{
public void printbmw()
{
System.out.println("我是欧洲的bmw");
}
}
class EuropeLinken extends Linken
{
public void printLinken()
{
System.out.println("我是欧洲的林肯");
}
}
class Asiacar extends MakecarFactory
{
public BMW createBMW()
{
return new AsiaBmw();
}
public Linken createLinken()
{
return new AsiaLinken();
}
}
class Europe extends MakecarFactory
{
public BMW createBMW()
{
return new EuropeBmw();
}
public Linken createLinken()
{
return new EuropeLinken();
}
}
class Test
{
private BMW bmw;
private Linken linken;
public Test(MakecarFactory factory)
{
bmw=factory.createBMW();
linken=factory.createLinken();
}
public void printsomething()
{
bmw.printbmw();
linken.printLinken();
}
}
public class CarFactory
{
public static void main(String[] args)
{
MakecarFactory asiacar=new Asiacar();
Test testcar=new Test(asiacar);
testcar.printsomething();
MakecarFactory europcar=new Europe();
testcar=new Test(europcar);
testcar.printsomething();
}
}