2004-11-10 星期三 晴
1. 什么是设计模式?
答:1) 设计模式是重用的解决方案;
2) 设计模式构建了一系列规则描述如何完成软件开发领域的适当任务;
3) 一个模式定位于一个特定设计环境出现的可重用设计问题并提供了一个解决方案;
2. 工厂模式
答:
public class CarCreateDemo {
public static void main(String[] args) {
CarCreate carCreate = new CarCreate();
AudiType audiType = new AudiType();
BWMType bwmType = new BWMType();
BenzType benzType = new BenzType();
carCreate.createCar(audiType);
carCreate.createCar(bwmType);
carCreate.createCar(benzType);
}
}
class CarCreate
{
public void createCar(ICarType carType) {
ICar car = carType.createCar();
car.createWheel();
car.createEngine();
car.createDoor();
}
}
interface ICarType {
ICar createCar();
}
class AudiType implements ICarType
{
public ICar createCar() {
return new Audi();
}
};
class BWMType implements ICarType
{
public ICar createCar() {
return new BWM();
}
};
class BenzType implements ICarType
{
public ICar createCar() {
return new Benz();
}
};
interface ICar {
void createWheel();
void createEngine();
void createDoor();
}
class Audi implements ICar
{
public void createWheel(){System.out.println("Create Audi Wheel");}
public void createEngine(){System.out.println("Create Audi Engine");}
public void createDoor(){System.out.println("Create Audi Door");}
};
class BWM implements ICar
{
public void createWheel(){System.out.println("Create BWM Wheel");}
public void createEngine(){System.out.println("Create BWM Engine");}
public void createDoor(){System.out.println("Create BWM Door");}
};
class Benz implements ICar
{
public void createWheel(){System.out.println("Create Benz Wheel");}
public void createEngine(){System.out.println("Create Benz Engine");}
public void createDoor(){System.out.println("Create Benz Door");}
};
3. Singleton模式
答:
public class ProductLineDemo
{
public static void main(String[] args){
ProductLine productLine1 = ProductLine.getProductLine();
ProductLine productLine2 = ProductLine.getProductLine();
productLine1.createProduct();
productLine2.createProduct();
}
};
class ProductLine extends Thread
{
static ProductLine instance = null;
int numberOfProduct = 0;
int maxProduct = 10;
private ProductLine(){};
public static ProductLine getProductLine(){
if(instance == null) {
instance = new ProductLine();
}
return instance;
}
public void createProduct() {
if (numberOfProduct < maxProduct) {
numberOfProduct ++;
System.out.println("这是今天生产的第" + numberOfProduct + "个产品!");
try{
sleep(300);
createProduct();
} catch(Exception e){
}
}
else {
System.out.println("今天已完成任务,喝茶去吧!");
}
}
}