Skip to content

Commit

Permalink
Bytecode pattern iluwatar#553 (iluwatar#896)
Browse files Browse the repository at this point in the history
* Added bytecode pattern

* Diagram changed and added licence information

* Added bytecode module to main pom.

* Fixed missing dependency error
  • Loading branch information
pzawitowski authored and iluwatar committed Sep 3, 2019
1 parent 7f6067f commit 318f811
Show file tree
Hide file tree
Showing 13 changed files with 819 additions and 0 deletions.
25 changes: 25 additions & 0 deletions bytecode/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
layout: pattern
title: Bytecode
folder: bytecode
permalink: /patterns/bytecode/
categories: Behavioral
tags:
- Java
- Difficulty-Beginner
---

## Intent
Allows to encode behaviour as instructions for virtual machine.

## Applicability
Use the Bytecode pattern when you have a lot of behavior you need to define and your
game’s implementation language isn’t a good fit because:

* it’s too low-level, making it tedious or error-prone to program in.
* iterating on it takes too long due to slow compile times or other tooling issues.
* it has too much trust. If you want to ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of the codebase.

## Credits

* [Game programming patterns](http://gameprogrammingpatterns.com/bytecode.html)
Binary file added bytecode/etc/bytecode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 49 additions & 0 deletions bytecode/etc/bytecode.ucls
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.2.3" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
<class id="1" language="java" name="com.iluwatar.bytecode.VirtualMachine" project="bytecode"
file="/bytecode/src/main/java/com/iluwatar/bytecode/VirtualMachine.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="455" y="173"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.bytecode.App" project="bytecode"
file="/bytecode/src/main/java/com/iluwatar/bytecode/App.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="148" y="110"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="3" language="java" name="com.iluwatar.bytecode.Wizard" project="bytecode"
file="/bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java" binary="false" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="148" y="416"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<association id="4">
<end type="SOURCE" refId="1" navigable="false" variant="ASSOCIATION">
<attribute id="5" name="wizards">
<position height="18" width="48" x="296" y="291"/>
</attribute>
<multiplicity id="6" minimum="0" maximum="2147483647">
<position height="0" width="0" x="-327" y="-27"/>
</multiplicity>
</end>
<end type="TARGET" refId="3" navigable="true" variant="ASSOCIATION"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>
45 changes: 45 additions & 0 deletions bytecode/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License
Copyright (c) 2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.21.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>bytecode</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
79 changes: 79 additions & 0 deletions bytecode/src/main/java/com/iluwatar/bytecode/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.bytecode;

import com.iluwatar.bytecode.util.InstructionConverterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as instructions
* for a virtual machine.
* An instruction set defines the low-level operations that can be performed. A series of instructions is encoded as
* a sequence of bytes. A virtual machine executes these instructions one at a time,
* using a stack for intermediate values. By combining instructions, complex high-level behavior can be defined.
*
* This pattern should be used when there is a need to define high number of behaviours and implementation engine
* is not a good choice because
* It is too lowe level
* Iterating on it takes too long due to slow compile times or other tooling issues.
* It has too much trust. If you want to ensure the behavior being defined can’t break the game,
* you need to sandbox it from the rest of the codebase.
*
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

/**
* Main app method
* @param args command line args
*/
public static void main(String[] args) {
VirtualMachine vm = new VirtualMachine();

Wizard wizard = new Wizard();
wizard.setHealth(45);
wizard.setAgility(7);
wizard.setWisdom(11);
vm.getWizards()[0] = wizard;

interpretInstruction("LITERAL 0", vm);
interpretInstruction( "LITERAL 0", vm);
interpretInstruction( "GET_HEALTH", vm);
interpretInstruction( "LITERAL 0", vm);
interpretInstruction( "GET_AGILITY", vm);
interpretInstruction( "LITERAL 0", vm);
interpretInstruction( "GET_WISDOM ", vm);
interpretInstruction( "ADD", vm);
interpretInstruction( "LITERAL 2", vm);
interpretInstruction( "DIVIDE", vm);
interpretInstruction( "ADD", vm);
interpretInstruction( "SET_HEALTH", vm);
}

private static void interpretInstruction(String instruction, VirtualMachine vm) {
InstructionConverterUtil converter = new InstructionConverterUtil();
vm.execute(converter.convertToByteCode(instruction));
LOGGER.info(instruction + String.format("%" + (12 - instruction.length()) + "s", "" ) + vm.getStack());
}
}
65 changes: 65 additions & 0 deletions bytecode/src/main/java/com/iluwatar/bytecode/Instruction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.bytecode;

/**
* Representation of instructions understandable by virtual machine
*/
public enum Instruction {

LITERAL(1),
SET_HEALTH(2),
SET_WISDOM (3),
SET_AGILITY(4),
PLAY_SOUND(5),
SPAWN_PARTICLES(6),
GET_HEALTH(7),
GET_AGILITY(8),
GET_WISDOM(9),
ADD(10),
DIVIDE (11);

private int value;

Instruction(int value) {
this.value = value;
}

public int getIntValue() {
return value;
}

/**
* Converts integer value to Instruction
* @param value value of instruction
* @return representation of the instruction
*/
public static Instruction getInstruction(int value) {
for (int i = 0; i < Instruction.values().length; i++) {
if (Instruction.values()[i].getIntValue() == value) {
return Instruction.values()[i];
}
}
throw new IllegalArgumentException("Invalid instruction value");
}
}
Loading

0 comments on commit 318f811

Please sign in to comment.