// producer.java
import java.util.ArrayList;
public interface Producer{
ArrayList<Integer> produce(int length);
}
// modelbase.java
abstract public classModelBase{
}
// model.java
import java.util.ArrayList;
class Model extends ModelBase{
private Producer producer;
void setProducer(Producer producer){
this.producer = producer;
}
ArrayList<Integer> test(int length){
return this.producer.producer(length);
}
}
1. 编写FibonacciProducer类,实现斐波那契数列
示例:
Model model = new Model();
model.setProducer(new FibonacciProducer());
System.out.print(model.test(10));
输出 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
2. 给model和producer的创建提供一些额外的自由度,编写ModelFactory类和ProducerFactory类
示例:
Model model = ModelFactory.create();
model.setProducer(ProducerFactory.create('fibonacci'));
System.out.print(model.test(10));
输出 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
这个面试题挺有意思的,所以我想保存一下,在面试的时候没想这么多,回家了以后,慢慢品味,感觉还是挺有意思的。下面开始实现。
1.
class FibonacciProducer implements Producer{
static int a = 0;
static int b = 1;
static int c = 0;
@Override
public ArrayList<Integer> produce(int length) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < length; i++) {
list.add(ret(i));
}
return list;
}
public static int ret(int value){
if( value < 2 ){
a = b;
return 1;
} else {
c = a + b;
a = b;
b = c;
return c;
}
}
}
2.
class ModelFactory{
public static ModelBase create(){
return new Model();
}
}
class ProducerFactory{
public static Producer create(String name){
if(name != null && name.equals("fibonacci")){
return new FibonacciProducer();
}
return null;
}
}