Created
April 17, 2025 16:41
-
-
Save thinkphp/d4f793e9620f67d65720bde3c3fa3249 to your computer and use it in GitHub Desktop.
Factory Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Modelul de Design Factory este un model creational care ofera o interfata pentru crearea obiectelor intr-o superclasa, dar permite | |
subclaselor sa modifice tipul obiectelor care vor fi create. Acest model este deosebit de util cand avem nevoie de un mod de a crea | |
diferite obiecte, dar dorim sa separam codul clientului de clasele concrete | |
*/ | |
abstract class Document { | |
protected String name; | |
protected String content; | |
public void setName(String name) { | |
this.name = name; | |
} | |
public void setContent(String content) { | |
this.content = content; | |
} | |
public abstract void save(); | |
} | |
class PDFDocument extends Document { | |
@Override | |
public void save() { | |
System.out.println("Saving PDF document: " + name); | |
System.out.println("Compressing and encrypting content"); | |
} | |
} | |
class WordDocument extends Document { | |
@Override | |
public void save() { | |
System.out.println("Saving Word document: " + name); | |
System.out.println("Formatting content"); | |
} | |
} | |
//Abstract Creator | |
abstract class DocumentFactory { | |
//Factory method | |
public abstract Document createDocument(); | |
//template method care foloseste metoda factory | |
public Document prepareDocument(String name, String content) { | |
Document document = createDocument(); | |
document.setName(name); | |
document.setContent(content); | |
return document; | |
} | |
} | |
//concret Creators | |
class PDFDocumentFactory extends DocumentFactory { | |
@Override | |
public Document createDocument() { | |
return new PDFDocument(); | |
} | |
} | |
class WordDocumentFactory extends DocumentFactory { | |
@Override | |
public Document createDocument() { | |
return new WordDocument(); | |
} | |
} | |
//client code | |
public class DocumentManagementSystem { | |
public static void main(String[] args) { | |
//create a PDF document | |
DocumentFactory pdfFactory = new PDFDocumentFactory(); | |
Document pdfdoc = pdfFactory.prepareDocument("Annual Raport","Financial data for 2025"); | |
pdfdoc.save(); | |
//create a Word document | |
DocumentFactory wordFactory = new WordDocumentFactory(); | |
Document worddoc = wordFactory.prepareDocument("Meeting Minutes","Topics discussed in April meeting"); | |
pdfdoc.save(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment