[关键字]:java,design pattern,设计模式,《Java与模式》,Abstract Factory,抽象工厂模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty ([email protected])
[正文]:
/**
* 抽象工厂:Button and Text of Windows and Unix
* @version 2009-4-11
* @author Winty(
[email protected])
*/
package pattern.abstractfactory;
public class AbstractFactory{
public static void main(String[] args){
Factory unix , win;
unix = new UnixFactory();
win = new WindowsFactory();
//创建Unix产品
Button btn1 = unix.createButton();
Text text1 = unix.createText();
System.out.println("");
//创建Windows产品
Button btn2 = win.createButton();
Text text2 = win.createText();
}
}
//产品等级1
abstract class Button{
protected String type;
public Button(){
type = "Button";
}
}
class UnixButton extends Button{
public UnixButton(){
System.out.println("Unix" + type);
}
}
class WindowsButton extends Button{
public WindowsButton(){
System.out.println("Windows" + type);
}
}
//产品等级2
abstract class Text{
protected String type;
public Text(){
type = "Text";
}
}
class UnixText extends Text{
public UnixText(){
System.out.println("Unix"+type);
}
}
class WindowsText extends Text{
public WindowsText(){
System.out.println("Windows"+type);
}
}
//抽象工厂
abstract class Factory{
public abstract Button createButton();
public abstract Text createText();
}
class UnixFactory extends Factory{
public Button createButton(){
return new UnixButton();
}
public Text createText(){
return new UnixText();
}
}
class WindowsFactory extends Factory{
public Button createButton(){
return new WindowsButton();
}
public Text createText(){
return new WindowsText();
}
}