最近看的java design pattern 都出自 Java design patterns 一书。
这个factory pattern 要取决于用户的输入来实例化不同的类。 而super class 可以是个interface ,也可以是个普通的类。
Usage in JDK: 值得一看
java.util.Calendar, ResourceBundle, and NumberFormat geninstance() methods use Factory pattern.
valueof() method in wrapper classes like Boolean, Integer etc.
下面是例子:
-
package factorypattern;
-
-
-
interface IMobile{
-
public void cost();
-
public void pictureCapacity();
-
public void batterPower();
-
}
-
-
class Lenovo implements IMobile{
-
-
@Override
-
public void cost(){
-
System.out.println("Lenovo Cost starts from 10000");
-
}
-
-
@Override
-
public void pictureCapacity(){
-
System.out.println("Lenovo camera capacity starts from 10MP");
-
-
}
-
-
@Override
-
public void batterPower(){
-
System.out.println("Lenovo battery power starts from 2500 MAH");
-
}
-
-
@Override
-
public String toString(){
-
return "Lenovo [toString()= " +super.toString() +" ]";
-
}
-
}
-
-
class Samsung implements IMobile{
-
-
@Override
-
public void cost(){
-
System.out.println("Samsung Cost starts from 6000");
-
}
-
-
@Override
-
public void pictureCapacity(){
-
System.out.println("Samsung camera capacity starts from 4MP");
-
-
}
-
-
@Override
-
public void batterPower(){
-
System.out.println("Samsung battery power starts from 1200 MAH");
-
}
-
-
}
-
-
public class FactoryPatternDemo {
-
static IMobile createMobile(String type){
-
IMobile mob=null;
-
if("len".equalsIgnoreCase(type)){
-
mob = new Lenovo();
-
System.out.println("Lenovo created");
-
}else if ("sam".equalsIgnoreCase(type)){
-
mob = new Samsung();
-
System.out.println("Samsung created");
-
}
-
return mob;
-
}
-
-
public static void main(String[] args){
-
Lenovo len = (Lenovo) createMobile("len");
-
len.batterPower();
-
System.out.println(len);
-
-
Samsung sam = (Samsung) createMobile("sam");
-
sam.cost();
-
System.out.println(sam);
-
}
-
}
阅读(560) | 评论(0) | 转发(0) |