您的位置:首页 > 其它

AbstractFactory抽象工厂设计模式

2009-06-26 18:20 549 查看
相必大家对设计模式听得比较多,可是究竟怎么运用可能大家还有点糊涂!

其实我认为gof23中设计模式就是4种,:第一种:接口作为参数传递,是传递实现了这个接口的对象

第二种:接口作为参数返回是返回这个接口的对象

第三种:抽象类作为参数传递是传递实现了这个抽象类的对象

第四种:抽象类作为参数返回是返回这个抽象类的对象

好了,不多说了,进行我们的第一种设计模式:抽象工厂模式:

需求图片说明:


AbstractFactory
public interface IAnimalFactory {

ICat createCat();

IDog createDog();
}


ConcreteFactory
public class BlackAnimalFactory implements IAnimalFactory {

public ICat createCat() {
return new BlackCat();
}

public IDog createDog() {
return new BlackDog();
}

}


public class WhiteAnimalFactory implements IAnimalFactory {

public ICat createCat() {
return new WhiteCat();
}

public IDog createDog() {
return new WhiteDog();
}

}


AbstractProduct
public interface ICat {

void eat();
}


public interface IDog {

void eat();
}


ConcreteProduct
public class BlackCat implements ICat {

public void eat() {
System.out.println("The black cat is eating!");
}

}


public class WhiteCat implements ICat {

public void eat() {
System.out.println("The white cat is eating!");
}

}


public class BlackDog implements IDog {

public void eat() {
System.out.println("The black dog is eating");
}

}


public class WhiteDog implements IDog {

public void eat() {
System.out.println("The white dog is eating!");
}

}


Client
public static void main(String[] args) {
IAnimalFactory blackAnimalFactory = new BlackAnimalFactory();
ICat blackCat = blackAnimalFactory.createCat();
blackCat.eat();
IDog blackDog = blackAnimalFactory.createDog();
blackDog.eat();

IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory();
ICat whiteCat = whiteAnimalFactory.createCat();
whiteCat.eat();
IDog whiteDog = whiteAnimalFactory.createDog();
whiteDog.eat();
}


result
The black cat is eating!
The black dog is eating!
The white cat is eating!
The white dog is eating!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: