public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}
return null;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
}
}
Inside Circle::draw() method. Inside Rectangle::draw() method.
Supplier circleSupplier = Circle::new; Circle circle = circleSupplier.get();
final static Map<String, Supplier> map = new HashMap<>();
static {
map.put("CIRCLE", Circle::new);
map.put("RECTANGLE", Rectangle::new);
}
public class ShapeFactory {
final static Map<String, Supplier> map = new HashMap<>();
static {
map.put("CIRCLE", Circle::new);
map.put("RECTANGLE", Rectangle::new);
}
public Shape getShape(String shapeType){
Supplier shape = map.get(shapeType.toUpperCase());
if(shape != null) {
return shape.get();
}
throw new IllegalArgumentException("No such shape " + shapeType.toUpperCase());
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
Supplier shapeFactory = ShapeFactory::new;
//call draw method of circle
shapeFactory.get().getShape("circle").draw();
//call draw method of Rectangle
shapeFactory.get().getShape("rectangle").draw();
}
}
Inside Circle::draw() method. Inside Rectangle::draw() method.
() -> new Circe(args)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有