欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工厂模式

程序员文章站 2022-07-14 08:55:03
...
//工厂模式就类似于接口,不同的产品有一个统一产品的接口,不同的工厂有一个统一的工厂接口
//面向接口编程的思想

public interface Cycle {  
    public void run();  
}


public class UniCycle implements Cycle {  
 
    @Override 
    public void run() {  
        // TODO Auto-generated method stub  
        System.out.println("Cycle Run");  
    }  
 



public class BiCycle implements Cycle {  
 
    @Override 
    public void run() {  
        // TODO Auto-generated method stub  
        System.out.println("BiCycle Run");  
    }  
 



public class TriCycle implements Cycle {  
 
    @Override 
    public void run() {  
        // TODO Auto-generated method stub  
        System.out.println("TriCycle Run");  
    }  
 



public interface CycleFactory {  
    public Cycle getCycle();  



public class UniCycleFactory implements CycleFactory {  
 
    @Override 
    public Cycle getCycle() {  
        // TODO Auto-generated method stub  
        return new UniCycle();  
    }  
 


public class BiCycleFactory implements CycleFactory {  
 
    @Override 
    public Cycle getCycle() {  
        // TODO Auto-generated method stub  
        return new BiCycle();  
    }  
 



public class TriCycleFactory implements CycleFactory {  
 
    @Override 
    public Cycle getCycle() {  
        // TODO Auto-generated method stub  
        return new TriCycle();  
    }  
 



public class FactoryTest {  
 
    /** 
     * @param args 
     */ 
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        run(new UniCycleFactory().getCycle());  
        run(new BiCycleFactory().getCycle());  
        run(new TriCycleFactory().getCycle());  
          
        run(new UniCycleFactory());  
        run(new BiCycleFactory());  
        run(new TriCycleFactory());  
    }  
      
    public static void run(Cycle cycle){  
        cycle.run();  
    }  
      
    public static void run(CycleFactory cycleFactory){  
        Cycle cycle = cycleFactory.getCycle();  
        cycle.run();  
    }  
 

相关标签: 工厂模式