Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- /*
- * Factory pattern : creating object on some conditions ->
- * condn 1 -> obj 1
- * condn 2 -> obj 2 ..
- *
- *
- * Abstract Factory : factory of factories
- * when we want to group different prodcuts
- * condn1 -> facotry 1 -> subcondn1 -> obj1
- * condn2 -> facotry 2 -> subcondn2-> obj2;
- */
- interface Shape{
- public void draw();
- }
- abstract class Factory{
- abstract Shape getShape(String input);
- abstract Vehicle getVehicle(String input);
- }
- class Circle implements Shape{
- public void draw(){
- System.out.println("Circle");
- }
- }
- class Rectangle implements Shape{
- public void draw(){
- System.out.println("Rectangle");
- }
- }
- class ShapeFactory extends Factory{
- Shape getShape(String input){
- if(input == "circle"){
- return new Circle();
- }else if(input == "rectangle"){
- return new Rectangle();
- }else{
- return new Circle();
- }
- }
- }
- interface Vehicle{
- public void run();
- }
- class Car implements Vehicle{
- public void run(){
- System.out.println("Car");
- }
- }
- class Bike implements Vehicle{
- public void run(){
- System.out.println("Bike");
- }
- }
- class VehicleFactory extends Factory{
- Vehicle getVehicle(String input){
- if(input == "car"){
- return new Car();
- }else if(input == "bike"){
- return new Bike();
- }else{
- return new Bike();
- }
- }
- }
- class AbstractFactory{
- Factory getFactory(String input){
- if(input == "shape"){
- return new ShapeFactory();
- }else{
- return new VehicleFactory();
- }
- }
- }
- public class Main{
- public static void main(String args[]) throws Exception{
- // factory pattern
- ShapeFactory shapeFactory = new ShapeFactory();
- Shape shape = shapeFactory.getShape("circle");
- shape.draw();
- // abstract facotry pattern
- AbstractFactory abstractFactory = new AbstractFactory();
- Factory vehicleFactory = abstractFactory.getFactory("vehicle");
- Vehicle vehicle = vehicleFactory.getVehicle("car");
- vehicle.run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement